关于字典的学习(三) — 嵌套

497 阅读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}

更符合现实的情形是,外星人不止三个,且每个外星人都是使用代码自动生成的。在下面的示例中,我们使用range()生成了30个外星人:

#创建一个空列表
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)
print("...")

#显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))

打印结果为:

{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

我们可以使用for循环和if语句来修改某些外星人的颜色。例如,要将前三个外星人修改为黄色的、速度为中等且值10个点,可以这样做:

#创建一个空列表
aliens= []
#创建30个外星人
for alien_number in range(0,30):
    new_alien = {'color': 'green','points': 5,'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10

#显示前五个
for alien in aliens[:5]:
    print(alien)
print("...")

打印结果为:

{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...

2.在字典中存储列表

需要将列表存储在字典中,而不是将字典存储在列表中。 例如:

pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms','extran cheese'],
    }

print("You ordered a " + pizza['crust'] + "-crust pizza " +
      "with the following toppings;")
for topping in pizza['toppings']:
    print("\t" + topping)

打印结果为:

You ordered a thick-crust pizza with the following toppings;
	mushrooms
	extran cheese

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。在本章前面有关喜欢的编程语言的示例中,如果将每个人的回答都存储在一个列表中,被调查者就可选择多种喜欢的语言。在这种情况下,当我们遍历字典时,与每个被调查者相关联的都是一个语言列表,而不是一种语言;因此,在遍历该字典的for循环中,我们需要再使用一个for循环来遍历与被调查者相关联的语言列表:

favorite_languages = {
    'zjb': ['python','ruby'],
    'zhang': ['c'],
    'zhangji': ['ruby','go'],
    'zhangjibin': ['java','python'],
    }

for name,languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
         print("\t" + language.title())

打印结果为:


Zjb's favorite languages are:
	Python
	Ruby

Zhang's favorite languages are:
	C

Zhangji's favorite languages are:
	Ruby
	Go

Zhangjibin's favorite languages are:
	Java
	Python

注意:列表和字典的嵌套层级不应太多。

3.在字典中存储字典

可在字典中嵌套字典,但这样做时,代码可能很快复杂起来。例如,如果有多个网站用户,每个都有独特的用户名,可在字典中将用户名作为键,然后将每位用户的信息存储在一个字典中,并将该字典作为与用户名相关联的值。在下面的程序中,对于每位用户,我们都存储了其三项信息:名、姓和居住地;为访问这些信息,我们遍历所有的用户名,并访问与每个用户名相关联的信息字典:

users = {
    'aeinstein': {
        'frist': 'zhang',
        'last': 'jibin',
        'location': 'princeton',
        },
     'mcurie': {
        'frist': 'wang',
        'last': 'xiaofan',
        'location': 'paris',
        },
    }

for username,user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['frist'] + " " + user_info['last']
    location = user_info['location']
    
    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())

打印结果为:

Username: aeinstein
	Full name: Zhang Jibin
	Location: Princeton

Username: mcurie
	Full name: Wang Xiaofan
	Location: Paris

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