alien_0 = {'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
>>>green
>>>5

字典用放在花括号 { } 中的一系列“键值对”表示,“键值对”是两个相关联的值。

指定键时Python将返回与之相关联的值。键和值之间用冒号分隔,键值对之间用逗号分隔。在字典中,存储多少个键值对都可以。 与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。

1.1添加键值对

alien_0 = {'color':'green','points':5}
print(alien_0)

alien_0['x_position'] = 25
alien_0['y_position'] = 22
print(alien_0)
>>>{'color': 'green', 'points': 5}
>>>{'color': 'green', 'points': 5, 'x_position': 25, 'y_position': 22}

使用字典来存储用户提供的数据或在编写能自动生成大量键值对的代码时,通常都需要先定义一个空字典。

alien_0 = { }

alien_0['color'] = 'green'
alien_0['point'] = 22
print(alien_0)
>>>{'color': 'green', 'point': 22}

1.2修改字典中的值 

alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
print("Original x_position: " + str(alien_0['x_position']))

if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x_pposition: " + str(alien_0['x_position']))

>>>Original x_position: 0
>>>New x_pposition: 2

1.3del语句删除键值对

alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
print(alien_0)
del alien_0['x_position']
print(alien_0)
>>>{'x_position': 0, 'y_position': 25, 'speed': 'medium'}
>>>{'y_position': 25, 'speed': 'medium'}

1.4拆分代码行格式

favorite_lauguages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("Sarah's favorite language is " +
      favorite_lauguages['sarah'].title() +
      ".")
>>>Sarah's favorite language is C.

2.1for循环遍历字典

user_0 = {
    'username':'efermi',
    'first':'enrico',
    'last':'fermi',
    }

for key,value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)
>>>Key: username
>>>Value: efermi

>>>Key: first
>>>Value: enrico

>>>Key: last
>>>Value: fermi

用于遍历字典的for 循环,可声明两个变量,用于存储键值对中的键和值。对于这两个变量,可使用任何名称。

方法items( ) ,它返回一个键值对列表。

遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。

2.2遍历字典中所有键keys( )

favorite_lauguages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }

for name in favorite_lauguages.keys():
    print(name.title())
>>>Jen
>>>Sarah
>>>Edward
>>>Phil

提取字典favorite_languages 中的所有键,并依次将它们存储到变量name中。

遍历字典时,会默认遍历所有的键,但显式地使用方法keys() 可让代码更容易理解,也可省略,其结果不变。

favorite_lauguages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
frineds = ['phil','sarah']
for name in favorite_lauguages.keys():
    if name in frineds:
        print(name.title()+ ",favorite language is " + favorite_lauguages[name].title())
>>>Sarah,favorite language is C
>>>Phil,favorite language is Python
favorite_lauguages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }

if 'erin' not in favorite_lauguages.keys():
    print("Erin,plesase take our poll!")
>>>Erin,plesase take our poll!

字典总是明确地记录键和值之间的关联关系,但获取字典的元素时,获取顺序是不可预测的。

2.3遍历字典中所有的值values( )

favorite_lauguages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }

for language in favorite_lauguages.values():
    print(language.title())
>>>Python
>>>C
>>>Ruby
>>>Python

2.4集合set()

这种做法提取字典中所有的值,而没有考虑是否重复。但如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的:

favorite_lauguages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }

for language in set(favorite_lauguages.values()):
    print(language.title())
>>>Ruby
>>>Python
>>>C

过对包含重复元素的列表调用set() ,可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。

3嵌套

将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套 。也可以在字典中嵌套字典。

3.1列表中包含字典:

alien_0 = {'color':'green','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}

aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)
>>>{'color': 'green', 'points': 5}
>>>{'color': 'yellow', 'points': 10}
>>>{'color': 'red', 'points': 15}
aliens = []
#创建30个绿色外星人
for alien_number in range(30):
    new_alien = {'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)
#显示前三个人
for alien in aliens[0:3]:
    print(alien)
>>>{'color': 'green', 'points': 5, 'speed': 'slow'}
>>>{'color': 'green', 'points': 5, 'speed': 'slow'}
>>>{'color': 'green', 'points': 5, 'speed': 'slow'}

3.2字典中嵌套列表:

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:
        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

注意:列表和字典的嵌套层级不应太多。如果嵌套层级比前面的示例多得多,很可能有更简单的解决问题的方案。

3.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("Full name: " + full_name.title())
    print("Location: " + location.title())
>>>Username: aeinstein
>>>Full name: Albert Einstein
>>>Location: Princeton
>>>Username: mcurie
>>>Full name: Marie Curie
>>>Location: Paris

注意:表示每位用户的字典的结构都相同,虽然Python并没有这样的要求,但这使得嵌套的字典处理起来更容易。倘若表示每位用户的字典都包含不同的键,for 循环内部的代码将更复杂。