So far, we have already introduced three container data types in Python: lists, tuples, and sets. But these data types are still not enough to help us solve all problems. For example, if we need one variable to save many pieces of information about a person, including name, age, height, weight, home address, personal mobile number, and emergency contact number, then you will find that the list, tuple, and set types we learned before are not good enough.
person1 = ['王大锤', 55, 168, 60, '成都市武侯区科华北路62号1栋101', '13122334455', '13800998877']
person2 = ('王大锤', 55, 168, 60, '成都市武侯区科华北路62号1栋101', '13122334455', '13800998877')
person3 = {'王大锤', 55, 168, 60, '成都市武侯区科华北路62号1栋101', '13122334455', '13800998877'}Sets are definitely the least suitable, because sets cannot have duplicate elements. If a person's age and weight happen to be the same, then the set will lose one piece of information. In the same way, if the person's phone number and emergency contact number are the same, the set will lose another piece of information. On the other hand, although lists and tuples can save all of a person's information, when you want to get this person's phone number or home address, you first need to know which element position contains that information. In short, in scenes like the one above, lists, tuples, and sets are not the most suitable choices. At this time, we need the dictionary type. This data type is most suitable for putting related information together, and it can help us solve the problem of modeling real things in Python programs.
The word "dictionary" should already be familiar. When we were in elementary school, almost everyone had a copy of the Xinhua Dictionary, as shown below.
The dictionary in Python is very much like a dictionary in real life. It organizes data together in the form of key-value pairs, and we can find the corresponding value through the key and work with it. Just like in the Xinhua Dictionary, each Chinese character has a matching explanation. Each character and its explanation together make one entry in the dictionary, and a dictionary usually contains many such entries.
In Python, we can create a dictionary with the {} literal syntax. This is the same as the set we talked about in the previous lesson. But the elements inside {} in a dictionary are key-value pairs. Each element is made of two values separated by :. The part before : is the key, and the part after : is the value, as shown below.
xinhua = {
'麓': '山脚下',
'路': '道,往来通行的地方;方面,地区:南~货,外~货;种类:他俩是一~人',
'蕗': '甘草的别名',
'潞': '潞水,水名,即今山西省的浊漳河;潞江,水名,即云南省的怒江'
}
print(xinhua)
person = {
'name': '王大锤',
'age': 55,
'height': 168,
'weight': 60,
'addr': '成都市武侯区科华北路62号1栋101',
'tel': '13122334455',
'emergence contact': '13800998877'
}
print(person)From the code above, you can probably already see that using a dictionary to save one person's information is much better than using a list or tuple, because we can use the key before : to show the meaning of the entry, and the value after : is the value that belongs to that entry.
Of course, if we want, we can also use the built-in function dict or dictionary-comprehension syntax to create dictionaries, as shown below.
person = dict(name='王大锤', age=55, height=168, weight=60, addr='成都市武侯区科华北路62号1栋101')
print(person) # {'name': '王大锤', 'age': 55, 'height': 168, 'weight': 60, 'addr': '成都市武侯区科华北路62号1栋101'}
items1 = dict(zip('ABCDE', '12345'))
print(items1) # {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5'}
items2 = dict(zip('ABCDE', range(1, 10)))
print(items2) # {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
items3 = {x: x ** 3 for x in range(1, 6)}
print(items3)If we want to know how many key-value pairs are in a dictionary, we still use the len function. If we want to iterate over a dictionary, we can use a for loop, but it should be noted that the for loop only iterates over the keys in the dictionary. It does not matter. After learning dictionary indexing operations, we can use the keys to access the corresponding values.
person = {
'name': '王大锤',
'age': 55,
'height': 168,
'weight': 60,
'addr': '成都市武侯区科华北路62号1栋101'
}
print(len(person)) # 5
for key in person:
print(key)For the dictionary type, membership operations and indexing operations are certainly very important. The former can determine whether a specified key is in the dictionary, and the latter can use a key to access the corresponding value or add a new key-value pair to the dictionary. It is worth noting that dictionary indexing is different from list indexing. The elements in a list have their own positions, so the index of a list is an integer. But because a dictionary saves key-value pairs, a dictionary needs to use keys to index the corresponding values. It is especially important to remind everyone that keys in a dictionary must be immutable types, such as integers (int), floating-point numbers (float), strings (str), and tuples (tuple). This is the same requirement that sets put on their elements. Clearly, the list (list) and set (set) types we talked about before cannot be used as keys in a dictionary, and the dictionary type itself also cannot be used as a key in another dictionary, because dictionaries are also mutable. But lists, sets, and dictionaries can all be used as values in a dictionary.
person = {
'name': '王大锤',
'age': 55,
'height': 168,
'weight': 60,
'addr': ['成都市武侯区科华北路62号1栋101', '北京市西城区百万庄大街1号'],
'car': {
'brand': 'BMW X7',
'maxSpeed': '250',
'length': 5170,
'width': 2000,
'height': 1835,
'displacement': 3.0
}
}
print(person)Look at the code below to understand dictionary membership operations and indexing operations.
person = {'name': '王大锤', 'age': 55, 'height': 168, 'weight': 60, 'addr': '成都市武侯区科华北路62号1栋101'}
print('name' in person) # True
print('tel' in person) # False
print(person['name'])
print(person['addr'])
person['age'] = 25
person['height'] = 178
person['tel'] = '13122334455'
person['signature'] = '你的男朋友是一个盖世垃圾,他会踏着五彩祥云去迎娶你的闺蜜'
print(person)
for key in person:
print(f'{key}:\t{person[key]}')If you use a missing key with indexing, Python raises KeyError.
Among the methods of the dictionary type, most of them are related to operations on key-value pairs. The get method can use a key to get the corresponding value. Different from indexing operations, when the specified key is not in the dictionary, the get method does not raise an exception. Instead, it returns None or a specified default value.
person = {'name': '王大锤', 'age': 25, 'height': 178, 'addr': '成都市武侯区科华北路62号1栋101'}
print(person.get('name')) # 王大锤
print(person.get('sex')) # None
print(person.get('sex', True)) # TrueIf we need to get all the keys in a dictionary, we can use the keys method. If we need to get all the values in a dictionary, we can use the values method. The dictionary also has a method named items. It puts keys and values together into 2-tuples, and using this method to iterate over the elements in a dictionary is also very convenient.
person = {'name': '王大锤', 'age': 25, 'height': 178}
print(person.keys()) # dict_keys(['name', 'age', 'height'])
print(person.values()) # dict_values(['王大锤', 25, 178])
print(person.items()) # dict_items([('name', '王大锤'), ('age', 25), ('height', 178)])
for key, value in person.items():
print(f'{key}:\t{value}')The update method of a dictionary can merge two dictionaries. For example, if there are two dictionaries x and y, when we execute x.update(y), for keys that are the same in x and y, the values in x will be updated with the values in y; and the key-value pairs that exist in y but not in x will be directly added to x, as shown below.
person1 = {'name': '王大锤', 'age': 55, 'height': 178}
person2 = {'age': 25, 'addr': '成都市武侯区科华北路62号1栋101'}
person1.update(person2)
print(person1) # {'name': '王大锤', 'age': 25, 'height': 178, 'addr': '成都市武侯区科华北路62号1栋101'}If you use Python 3.9 or later, you can also use the | operator to do the same thing, as shown below.
person1 = {'name': '王大锤', 'age': 55, 'height': 178}
person2 = {'age': 25, 'addr': '成都市武侯区科华北路62号1栋101'}
person1 |= person2
print(person1) # {'name': '王大锤', 'age': 25, 'height': 178, 'addr': '成都市武侯区科华北路62号1栋101'}We can use the pop or popitem method to delete elements from a dictionary. The former returns the value corresponding to the key, but if the specified key does not exist in the dictionary, it raises KeyError. The latter returns a 2-tuple made up of the key and value while deleting the element. The clear method of a dictionary will clear all key-value pairs in the dictionary, as shown below.
person = {'name': '王大锤', 'age': 25, 'height': 178, 'addr': '成都市武侯区科华北路62号1栋101'}
print(person.pop('age')) # 25
print(person) # {'name': '王大锤', 'height': 178, 'addr': '成都市武侯区科华北路62号1栋101'}
print(person.popitem()) # ('addr', '成都市武侯区科华北路62号1栋101')
print(person) # {'name': '王大锤', 'height': 178}
person.clear()
print(person) # {}Just like with lists, we can also use the del keyword to delete elements from a dictionary. If the specified key cannot find a matching value when deleting an element, it will also raise KeyError, as shown below.
person = {'name': '王大锤', 'age': 25, 'height': 178, 'addr': '成都市武侯区科华北路62号1栋101'}
del person['age']
del person['addr']
print(person) # {'name': '王大锤', 'height': 178}We can use a few simple examples to see how to use the dictionary type to solve some real problems.
Example 1: Input a passage and count how many times each English letter appears. Output the result from high to low by count.
sentence = input('请输入一段话: ')
counter = {}
for ch in sentence:
if 'A' <= ch <= 'Z' or 'a' <= ch <= 'z':
counter[ch] = counter.get(ch, 0) + 1
sorted_keys = sorted(counter, key=counter.get, reverse=True)
for key in sorted_keys:
print(f'{key} 出现了 {counter[key]} 次.')Example 2: In a dictionary, save stock codes and prices. Find the stocks whose price is greater than 100 yuan and create a new dictionary.
Note: We can use dictionary-comprehension syntax to create this new dictionary.
stocks = {
'AAPL': 191.88,
'GOOG': 1186.96,
'IBM': 149.24,
'ORCL': 48.44,
'ACN': 166.89,
'FB': 208.09,
'SYMC': 21.29
}
stocks2 = {key: value for key, value in stocks.items() if value > 100}
print(stocks2)Dictionaries in Python are very similar to dictionaries in real life. They let us save data in the form of key-value pairs, and then use keys to access the matching values. A dictionary is a data type that is very convenient for data lookup, but it must be emphasized again that keys in a dictionary must be immutable types. Data such as lists, sets, and dictionaries themselves cannot be used as dictionary keys.
