Python(3)-字典

1.字典基本操作
在Python中,字典是一系列键—值对。每一个键都与一个值相关联,可以使用键来访问与之相关联的值。
用法举例:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color’])  取某个键关联的数值
alien_0['x_position'] = 12 添加值到字典
alien_0['color'] = ‘yellow' 修改字典里某个键关联的数值
del alien_0['points’] 从字典alien_0中删除键points及其值
 
2.遍历字典
2.1遍历字典所有键和值
user_0 = {
    'username': 'efermi’,
    'first': 'enrico’,
    'last': 'fermi’,
    }
for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)
结果:
Key: last
Value: fermi
 
Key: first
Value: enrico
 
Key: username
Value: efermi
key value也可以用其他好理解的命名
 
2.2遍历字典所有键
(1)for name in user_0.keys():
    print(name)
(2)if 'erin' not in user_0.keys() 判断erin不是user_0字典的key
 
2.3按顺序遍历字典中的所有键
favorite_languages = {
    'jen': 'python’,
    'sarah': 'c’,
    'edward': 'ruby’,
    'phil': 'python',}
for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.”)
结果:
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
 
2.4遍历字典中所有值
(1)for name in dic.values():
(2)for name in set(dic.values()):  剔除值的重复项,使用集合set,让Python找出列表独一无二的元素,并使用这些元素来创建一个集合。
 
3.嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,称为嵌套。
(1)在列表中存储字典
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow’}                  
    aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[:5]:
    print(alien)
将字典new_alien嵌套到列表aliens里。
 
(2)在字典中存储列表
举例:
favorite_languages = {
    'jen': ['python', 'ruby’],
    'sarah': ['c’],
    'edward': ['ruby', 'go’],
    'phil': ['python', 'haskell’],
    }
for name, languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:”)
        for language in languages:
            print("\t" + language.title())
 
(3)在字典中存储字典
举例,对于每位用户存储了其三项信息,名、姓和居住地,为访问这些信息,遍历所有用户名,并访问与每个用户名相关的信息字典,如下:
users = {
    'aeinstein': {
        'first': 'albert’,
        'last': 'einstein’,
        'location': 'princeton’,
        },
    'mcurie': {
        'first': 'marie’,
        'last': 'curie’,
        'location': 'paris’,
        },
    }
for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + " " + user_info['last’]
    location = user_info['location']
    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())
结果:
Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton
Username: mcurie
    Full name: Marie Curie
    Location: Paris
posted @ 2018-05-28 17:29  Tester-blanche  阅读(162)  评论(0编辑  收藏  举报