【Python】Collection - dict

Posted by 西维蜀黍 on 2019-11-01, Last Modified on 2024-05-02

dict

一个非常有用的 Python 內置数据类型是 字典 (参见 映射类型 — dict)。字典在其他语言里可能会被叫做 联合内存联合数组。与以连续整数为索引的序列不同,字典是以 关键字 为索引的,关键字可以是任意不可变类型,通常是字符串或数字。如果一个元组只包含字符串、数字或元组,那么这个元组也可以用作关键字。但如果元组直接或间接地包含了可变对象,那么它就不能用作关键字。列表不能用作关键字,因为列表可以通过索引、切片或 append()extend() 之类的方法来改变。

理解字典的最好方式,就是将它看做是一个 键: 值 对的集合,键必须是唯一的(在一个字典中)。一对花括号可以创建一个空字典:{} 。另一种初始化字典的方式是在一对花括号里放置一些以逗号分隔的键值对,而这也是字典输出的方式。

字典主要的操作是使用关键字存储和解析值。也可以用 del 来删除一个键值对。如果你使用了一个已经存在的关键字来存储值,那么之前与这个关键字关联的值就会被遗忘。用一个不存在的键来取值则会报错。

对一个字典执行 list(d) 将返回包含该字典中所有键的列表,按插入次序排列 (如需其他排序,则要使用 sorted(d))。要检查字典中是否存在一个特定键,可使用 in 关键字。

以下是使用字典的一些简单示例

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

通过 key 获取 value

如果key不存在,dict就会报错:

>>> d['Thomas']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Thomas'

要避免key不存在的错误,有两种办法,一是通过in判断key是否存在:python

>>> 'Thomas' in d
False

二是通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:

>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1

注意:返回None的时候Python的交互环境不显示结果。

删除 key

要删除一个key,用pop(key)方法,对应的value也会从dict中删除:

# 如果这个key不存在,删除时会抛异常
>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85}
>>> a.pop('Bob')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Bob'

# Syntax 2 - 如果这个key不存在,删除时不会抛异常
>>> dict.pop(key, defaultVal)

>>> a[1] =2
>>> del a[1]
>>> del a[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1

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

del alien_0['points'] 
print(alien_0)

迭代 dict

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...     print(key)
...
a
c
b

>>> for key in d.keys():
...     print(key)
...
a
c
b

for key, value in dictionary_unique.items():  #accessing keys
    print(key,end=',')

默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values()

当在字典中循环时,用 items() 方法可将关键字和对应的值同时取出

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

Adding New Key-Value Pairs

Dictionaries are dynamic structures, and you can add new key-value pairs to a dictionary at any time. For example, to add a new key-value pair, you would give the name of the dictionary followed by the new key in square brackets along with the new value.

Let’s add two new pieces of information to the alien_0 dictionary: the alien’s x- and y-coordinates, which will help us display the alien in a particular position on the screen. Let’s place the alien on the left edge of the screen, 25 pixels down from the top. Because screen coordinates usually start at the upper-left corner of the screen, we’ll place the alien on the left edge of the screen by setting the x-coordinate to 0 and 25 pixels from the top by setting its y-coordinate to positive 25, as shown here:

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

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

Misc

# combine all values into a list
>>> a = {1:[1,2],2:[2,3]}
>>> a.values()
dict_values([[1, 2], [2, 3]])

>>> list(a.values())
[[1, 2], [2, 3]]

#################################
# To access the key value pair, you would use the .items() method, which will return a list of dict_items in the form of a key, value tuple pairs.
{1: 3, 2: 2, 3: 1}.items()
dict_items([(1, 3), (2, 2), (3, 1)])
# To access keys and values separately, you could use a for loop on the dictionary or the .keys() and .values() method.
>>>{1: 3, 2: 2, 3: 4}.keys()
dict_keys([1, 2, 3])
>>> {1: 3, 2: 2, 3: 4}.values()
dict_values([3, 2, 4])

####################################
# sort
# only the keys will be returned
>>> my_dict = { 'num6': 6, 'num3': 3, 'num2': 2, 'num4': 4, 'num1': 1, 'num5': 5}
>>> sorted(my_dict)
['num1', 'num2', 'num3', 'num4', 'num5', 'num6']

# sort by values
>>> footballers_goals = {'Eusebio': 120, 'Cruyff': 104, 'Pele': 150, 'Ronaldo': 132, 'Messi': 125}
>>> sorted(footballers_goals.items(), key=lambda x:x[1])
[('Cruyff', 104), ('Eusebio', 120), ('Messi', 125), ('Ronaldo', 132), ('Pele', 150)]

# reversely sort
>>> footballers_goals = {'Eusebio': 120, 'Cruyff': 104, 'Pele': 150, 'Ronaldo': 132, 'Messi': 125}
>>> sorted(footballers_goals.items(), key=lambda x:x[1], reverse=True)
[('Pele', 150), ('Ronaldo', 132), ('Messi', 125), ('Eusebio', 120), ('Cruyff', 104)]

# extract keys, and sort
>>> sorted(footballers_goals.keys())
['Cruyff', 'Eusebio', 'Messi', 'Pele', 'Ronaldo']

# extract values, and sort
>>> sorted(footballers_goals.values())
[104, 120, 125, 132, 150]

Reference

  • Learning Python
  • Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming