Python数据类型(字典和集合),,1.5 Dictio


1.5 Dictionary(字典)

Python中,字典用放在花括号{}中一系列键-值对表示。键和值之间用冒号分隔,键-值对之间用逗号分隔。
在字典中,你想存储多少个键-值对都可以。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。

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

注意,键-值对的排列顺序与添加顺序不同。
Python不关心键-值对的添加顺序,而只关心键和值之间的关联关系。

>>> alien_0 = {} # 创建空字典>>> alien_0['color'] = 'green'>>> alien_0['point'] = 5>>> print(alien_0){'color': 'green', 'point': 5}

1.5.1 访问字典中的值

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

1.5.2 修改字典中的值

>>> alien_0 = {'color': 'green'}>>> alien_0['color']'green'>>> alien_0['color'] = 'yellow'>>> alien_0['color']'yellow'

1.5.3 删除键-值对

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

1.5.4 遍历字典

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# 
# 遍历字典中的所有键favorite_languages = {    'jen': 'python',    'sarah': 'c',    'edward': 'ruby',    'phil': 'python',}for name in favorite_languages.keys():    print(name.title())# Jen# Sarah# Edward# Phil
# 遍历字典中的所有值favorite_languages = {    'jen': 'python',    'sarah': 'c',    'edward': 'ruby',    'phil': 'python',}for language in favorite_languages.values():    print(language.title())# Python# C# Ruby# Python
favorite_languages = {    'jen': 'python',    'sarah': 'c',    'edward': 'ruby',    'phil': 'python',}# 通过方法set()来剔除重复项for language in set(favorite_languages.values()):    print(language.title())# C# Ruby# Python
favorite_languages = {    'jen': 'python',    'sarah': 'c',    'edward': 'ruby',    'phil': 'python',}# 使用in或者not in来判断key是否存在if 'erin' not in favorite_languages.keys():    print("Erin, please take our poll!")# Erin, please take our poll!
# 按顺序遍历字典中的所有键favorite_languages = {    'jen': 'python',    'sarah': 'c',    'edward': 'ruby',    'phil': 'python',}for name in sorted(favorite_languages.keys()):    print(name.title())# Edward# Jen# Phil# Sarah

1.5.5 嵌套

你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

# 在列表中嵌套字典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}
# 在字典中嵌套列表pizza = {    'crust': 'thick',    'toppings': ['mushrooms', 'extra 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#   extra cheese
# 在字典中嵌套字典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

1.6 Set(集合)

集合是一个无序的不重复元素序列。
可以使用大括号{}或者set()函数创建集合。
注意:创建一个空集合必须用set()而不是{},因为{}是用来创建一个空字典。

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}>>> print(basket){'orange', 'apple', 'pear', 'banana'}>>> 'orange' in basketTrue>>> 'crabgrass' in basketFalse

两个集合之间的运算

>>> a = set('abracadabra')>>> b = set('alacazam')>>> a{'a', 'b', 'c', 'd', 'r'}>>> b{'l', 'z', 'm', 'a', 'c'}>>> a - b{'b', 'd', 'r'}>>> a | b{'l', 'z', 'a', 'm', 'b', 'c', 'd', 'r'}>>> a & b{'a', 'c'}>>> a ^ b{'b', 'l', 'z', 'd', 'm', 'r'}

1.6.1 添加元素

>>> thisset = set(("Google", "Runoob", "Taobao"))>>> print(thisset){'Runoob', 'Google', 'Taobao'}>>> thisset.add("Facebook")>>> print(thisset){'Runoob', 'Facebook', 'Google', 'Taobao'}

使用update()方法也可以添加元素,而且参数可以是列表、元组、字典等。

>>> thisset = set(("Google", "Runoob", "Taobao"))>>> thisset.update({1,3})>>> print(thisset){'Runoob', 1, 3, 'Taobao', 'Google'}>>> thisset.update([1,4],[5,6])>>> print(thisset){'Runoob', 1, 3, 4, 'Taobao', 'Google', 5, 6}

1.6.2 移除元素

>>> thisset = set(("Google", "Runoob", "Taobao"))>>> thisset.remove("Taobao")>>> print(thisset){'Google', 'Runoob'}
>>> thisset = set(("Google", "Runoob", "Taobao"))>>> thisset.discard("Facebook")  # 不存在不会发生错误>>> print(thisset){'Runoob', 'Google', 'Taobao'}
>>> thisset = set(("Google", "Runoob", "Taobao", "Facebook"))>>> x = thisset.pop() # 随机删除集合中的一个元素>>> print(x)Google

1.6.3 清空集合

>>> thisset = set(("Google", "Runoob", "Taobao"))>>> thisset.clear()>>> print(thisset)set()

1.6.4 计算集合元素个数

>>> thisset = set(("Google", "Runoob", "Taobao"))>>> len(thisset)3

参考资料:

Python3 教程 | 菜鸟教程Python教程 - 廖雪峰的官方网站《Python编程从入门到实践》——【美】Eric Matthes 著

Python数据类型(字典和集合)

评论关闭