【Python编程:从入门到实践】chapter6 字典

chapter6 字典
6.1 一个简单的字典
6.2 使用字典
6.2.1 访问字典中的值
6.2.2 添加键值对
6.2.3 先创建一个空字典
6.2.4 修改字典中的值
6.2.5 删除键值对
del alien['points']
6.2.6 由类似对象组成的字典
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
6.3 遍历字典
6.3.1 遍历所有的键-值对
for key, value in favorite_languages.items():
print('key' + key)
print('value' + value)
python不关心键-值对的存储顺序,而只跟踪键和值之间的关系。
6.3.2 遍历字典中所有的键
for name in favorite_languages.keys():
print(name.title())
6.3.3 按顺序遍历字典中所有键
for name in sorted(favorite_languages.keys()):
print(name.title())
6.3.4 遍历字典中所有的值
for language in favorite_languages.values():
print(language.title())
这种做法提取字典中所有的值,而没有考虑是否重复。为了剔除重复项,可使用集合(set).
for language in set(favorite_languages.values()):
print(language.title())
6.4 嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这成为嵌套
6.4.1 字典列表
alien_0 = {'color':'green','points':5}
alien_1 = {'color':'green','points':5}
alien_2 = {'color':'green','points':5}

aliens = [alien_0, alient_1, alien_2]
for alien in aliens:
print(alien)

eg:
aliens = []
for alien_number in range(30):
new_alien = {'color':'green','points':5}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print('...')
print('Total number of aliens:' + str(len(aliens)))
6.4.2 在字典中存储列表
pizza = {
'crust':'thick',
'toppings':['nushrooms','extra cheese']
}
for topping in pizza['toppings']
print(topping)
6.4.3 在字典中存储字典
user = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
}
}

for name, user_info in user.items():
print(name)
print(user_info['first'])
print(user_info['last'])
print(user_info['location'])

for key,value in user_info.items():
print(key)
print(value)

作者:长风 Email:844064492@qq.com QQ群:607717453 Git:https://github.com/zhaohu19910409Dz 开源项目:https://github.com/OriginMEK/MEK 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利. 感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。 如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!
原文地址:https://www.cnblogs.com/zhaohu/p/8099772.html