1.字典:
在Python中,字典 是一系列键—值对 。每个键都与一个值相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。在Python中,字典用放在花括号{} 中的一系列键—值对表示
键—值 对是两个相关联的值。指定键时,Python将返回与之相关联的值。键和值之间用冒号分隔,而键—值对之间用逗号分隔。在字典中,你想存储多少个键—值对都可以。最简单的字典只有一个键-值对
#1.1访问字典中的值
pets = {'name': 'xixi'}
print(pets['name'])
#输出 xixi
#1.2 添加键-值对
pets = {'name': 'xixi'}
pets['color'] = green
#1.3创建空字典
#可先使用一对空的花括号定义一个空字典,再分行添加各个键—值对
pets = {}
pets['color'] = green
pets['name'] = xixi
#1.4修改字典中的值
pets = {'name': 'xixi'}
print("The pet name is " + pets['name'] + ".")
pets['color'] = green
print("The pet color is " + pets['color'] + ".")
#1.5删除键-值对
#可使用del 语句将相应的键—值对彻底删除
pets = {'name': 'xixi'}
del pets['name']
2.一个简单的字典:
pets = {'color': 'green', 'name':kiki}
print(pets['color'])
print(pets['name'])
打印出的结果为:green xixi
3.遍历字典:
3.1遍历所有的键-值对 key value
pets = {'name': 'xixi','age':'3','color':'white'}
for key, value in pets.items():
print("\nKey: " + key)
print("Value: " + value)
要编写用于遍历字典的for 循环,可声明两个变量key和value,用于存储键—值对中的键和值。对于这两个变量,可使用任何名称。
3.2遍历所有的键和值,在不需要使用字典中的值时,使用方法keys() ,不需要键的时候,使用方法values()
pets = {'name': 'xixi','age':'3','color':'white'}
for name in pets.keys(): 也可以写成for name in pets: 输出将不变。
for name in favorite_languages.values(): //遍历所有值,这种做法提取字典中所有的值,没有考虑是否重复 ,如果改成for name in set(favorite_languages.values()): ,可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合
3.3按顺序遍历字典中的所有键
可使用函数sorted()
pets = {'name': 'xixi','age':'3','color':'white'}
for name in sorted(pets.keys()):
print(name.title() )
4.嵌套:
需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。
4.1字典列表
pets0 = {'name': 'xixi','age':'3','color':'white'}
pets1 = {'name': 'kk','age':'1','color':'white'}
pets = [pets0,pets1]
4.2在字典中存储列表:
4.3在字典中存储字典