Python 入门日记(六)—— 字典

2020.07.12 Python 入门的 Day5

成就:字典(不就是个 struct 嘛)

  • 字典举例:
aline_0 = {'color':'green', 'points':5}
# aline_0 是一个的字典,包含 color 和 points 两个信息
print(aline_0['color'])
print(aline_0['points'])
  • 在 Python 中,字典是一系列的键—值对,每个键都与一个值相关联,可通过键来访问相关的值。
  • 添加键—值对时,可依次指定字典名、用方括号括起来的键和与之相关联的值。
aline_0['x_position'] = 0
aline_0['y_position'] = 25
# 直接添加就可以,简单粗暴
print(aline_0)
  • 修改键—值对时,可依次指定字典名、用方括号括起来的键以及与之相关联的值。
aline_0['color'] = 'yellow'
# 直接修改,简单粗暴
  • 删除键—值对时,使用 del 语句将相应的键—值对彻底删除。
del aline_0['color']
# 简单粗暴
  • 由类似对象组成的字典:
favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
}
# 注意缩进,以及逗号
# 建议在最后一个键—值对的后面也加一个逗号
# 方便另外添加键—值对
  • 用 for 循环遍历字典,方法 items() 可将字典生成列表:
favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
}
# 定义一个字典
for Name, Language in favorite_language.items():
    print(Name.title() + "'s favorite language is " + Language.title())
# 有两个临时变量, Name 指示键, Language 指示相对应的值
  •  遍历字典中的所有键,用方法 keys() ;遍历所有的值,用方法 values()。
for Name in favorite_language.keys():
    print("Name:" + Name.title())

for Name in sorted(favorite_language.keys()):
    print("Name:" + Name.title())
  • 可使用函数 sorted() 来是按照一定的顺序遍历所有键。
for Name in sorted(favorite_language.keys()):
    print("Name:" + Name.title())
  • 可使用函数 set() 消除键中的重复项。
for Language in set(favorite_language.values()):
    print("Language:" + Language.title())
  • 使用列表保存字典。
alines = []
# 创建一个空列表
for aline_number in range(30)[1:15]:
    new_aline = {'color':'green', 'points':5, 'speed':'slow'}
    alines.append(new_aline)
# 添加列表中的字典
for aline in alines[:]:
    print(aline)
  • 在字典中储存列表。
pizza = {
    'crust':'thick',
    'toppings':['mushroom', 'extra cheese'],
}

print("You ordered a " + pizza['crust'] + "-crust pizza" +
      "with the following toppings:")
for topping in pizza['toppings']:
    print("	" + topping.title())
  • 在字典中储存字典。
users = {
    'asinstein':{
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },
    'mcurie':{
        'first': 'maire',
        'last': 'curie',
        'location': 'paris',
    },
}
for username, user_info in users.items():
    print("
Username: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    print("	Full name: " + full_name.title())
    print("	Location: " + location.title())
原文地址:https://www.cnblogs.com/A-Tree/p/13287660.html