**1.基本表示 **
alien={'color':'green','points':5}
其中包含若干对 键-值对
2.访问字典中的值
print(alien['color'])
指定键时,字典会返回相对应的值
注意其中的 键需要用 方括号[key]
3.添加键-值对
>>> alien['x-position']=0
>>> alien['y-position']=1
>>> print(alien)
{'color': 'green', 'points': 5, 'x-position': 0, 'y-position': 1}
⚠️添加键-值对注意事项:1.键key 依然是用方括号
2.对应关系用“=”而不用“:”表示
Python不关心键-值对的添加顺序,只关心其中键-值对的关联关系
4.可以先创建空字典再进行补充
alien={}
5.修改,删除键值对
alien['color']='yellow'
del alien['color']
注意选定的对象始终是键key。
遍历字典
favorite_languages = {
'ben': 'c',
'bob': 'python',
'jen': 'java',
'nancy': 'python',
'lucy': 'ruby',
}
for name, language in favorite_languages.items():
print('\na person whose name is '+name.title()+',his favorite language is '+language.upper())
>a person whose name is Ben,his favorite language is C
a person whose name is Bob,his favorite language is PYTHON
a person whose name is Jen,his favorite language is JAVA
a person whose name is Nancy,his favorite language is PYTHON
a person whose name is Lucy,his favorite language is RUBY
注意这里需要加上dictionary.items(), 否则无法unpack
当不需要使用值时:
需要使用dictionary.keys():
favorite_languages = {
'ben': 'c',
'bob': 'python',
'jen': 'java',
'nancy': 'python',
'lucy': 'ruby',
}
for name in favorite_languages.keys():
print('\na person whose name is '+name.title())
>a person whose name is Ben
a person whose name is Bob
a person whose name is Jen
a person whose name is Nancy
a person whose name is Lucy
当然,遍历字典时,默认会遍历所有的键,如:
favorite_languages = {
'ben': 'c',
'bob': 'python',
'jen': 'java',
'nancy': 'python',
'lucy': 'ruby',
}
for name in favorite_languages:
print('\na person whose name is '+name.title())
输出结果与上式相同。
对于keys(),该方法不止用于遍历,实际上,它返回一个包含字典中所有键的列表。
如果只想获取值,那么将keys替换为values()。
按顺序遍历
一般来讲,获取字典的元素时,获取顺序是不可预测的,特定顺序排序可用 sorted(x)
具体代码:
for name in sorted(favorite_languages.keys()):
print...