《Python编程:从入门到实践(第二版)》自学笔记(九)

嵌套

有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。现实情况中在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

首先,字典列表就是字典放在列表中,先小字典,后大列表

1
2
3
4
5
6
7
8
9
10
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}

其次,列表字典就是列表放在字典中,先小列表,后大字典

1
2
3
4
5
6
7
8
9
10
11
12
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
print(f"You ordered a {pizza['crust']}-crust pizza "
"with the following toppings:")
for topping in pizza['toppings']:
print("\"+topping)
输出:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese

如果函数调用print()中的字符串很长,可以在合适的位置分行。只需要在每行末尾都加上引号,同时对于除第一行外的其他各行,都在行首加上引号并缩进。这样,Python将自动合并圆括号内的所有字符串,如上第一次的print输出

那么在什么样的情况下使用到列表字典?一般是字典中的键关联了多个值,此时可以直接使用。如:键-topping所对应的值有多个,那么久可以使用键与列表相关联,然后将键的值放入列表中。下面看一个稍微复杂一点点的逻辑代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
favorite_languages = { 
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{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

在这里可以尝试对上面示例的代码进行优化,使其更加轻量化。思路:可在遍历字典的 for 循环开头添加一条 if 语句,通过查看 len(languages) 的值来确定当前的被调查者喜欢的语言是否有多种。如果他喜欢的语言有多种,就像以前一样显示输出;如果只有一种,就相应修改输出的措辞,如显示 Sarah’s favorite language is C。后期时间来的及的话,我会把在PyCharm上执行的结果更新上。

最后,字典字典就是在字典放在字典中,先小字典,后大字典。但需要注意的是:在字典中嵌套字典,代码可能很快复杂起来,所以一般情况下不建议使用此嵌套,逼不得已最终使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
users = { 
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},

'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
输出:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton

Username: mcurie
Full name: Marie Curie
Location: Paris
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2019-2024 Carrol Chen
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信