建立空字典
alien_0 = {}
print(alien_0)
输出:
{}
删除键值对
alien_0 = {'color': 'green','points':'5'} del alien_0['color'] print(alien_0) 输出: {'points': '5'}
遍历键值对
user_0 = { 'username':'efermi', 'first':'enrico', 'last':'fermi' } for key,value in user_0.items(): print(" Key: " + key) print("Value: " + value) 输出: Key: username Value: efermi Key: first Value: enrico Key: last Value: fermi
遍历字典中的所有键
favorite_languages = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python' } for name in favorite_languages.keys():
#上行等同于:for name in favorite_languages: #(遍历字典时,会默认遍历所有的键)
print(name.title()) 输出: Jen Sarah Edward Phil
遍历字典中的所有值
favorite_languages = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python' } for value in set(sorted(favorite_languages.values())): #values():取值;sorted():排序;set():剔重 print(value.title()) 输出: Ruby C Python
嵌套:
字典中嵌套列表:打印每人最爱的语言
favorite_languages= { 'jen':['python','ruby'], 'sarah':['c'], 'edward':['ruby','go'], 'phil':['python','haskell'] } for name,languages in favorite_languages.items(): print(' ' + name.title() + "'s favorite languages are:" ) for language in languages: #注意:language与lanuages不同 print(" " + language.title()) 输出: Jen's favorite languages are: Python Ruby Sarah's favorite languages are: C Edward's favorite languages are: Ruby Go Phil's favorite languages are: Python Haskell
字典中嵌套字典:
users = { 'aeinstein':{ 'first':'albert', 'last':'einstein', 'location':'princeton' }, 'mcurie':{ 'first':'marie', 'last':'curie', 'location':'paris' } } for keys,values in users.items(): print(" " + keys + ":") full_name = values['first'] +' ' + values['last'] location = values['location'] print(" full_name: " + full_name) print(" location: " + location) 输出: aeinstein: full_name: albert einstein location: princeton mcurie: full_name: marie curie location: paris