leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python dictionary (dict) intensive

Estimated reading: 6 minutes 69 views

A dictionary is another data type in Python that can also store a set of data. Unlike lists and tuples, it can store objects of any type, such as strings, numbers, lists, and tuples and other data types.

Like lists, dictionaries contain many values. But unlike lists, dictionaries can use not only integers as indexes, but also other data types as indexes. We call the index of an element in the dictionary “key”, the content of the element the “value”, and the associated “key” and “value” as a “key-value” pair.

It’s like looking up a dictionary, we always have to first check the spelling by pinyin or strokes to find the explanation of a Chinese character and related words – the spelling of pinyin or strokes is the different “keys” of the dictionary; while Chinese characters and The interpretation of the associated word is the “value” of the element of the dictionary. Through this analogy, you can see why this data type is called a dictionary.

Python create dictionary

In Python, a dictionary is represented by a series of key-value pairs enclosed in curly braces, with the key and value in :each key-value pair separated by a colon and each key-value pair separated by a comma, in the following format Show:

>>> print(person)
{'name': 'Johnson', 'age': 9, 'gender': 'male', 'height': '140cm'}

We assign a dictionary to the variable person, the keys in the dictionary are “name”, “age”, “gender” and “height”, and the corresponding values ​​are “Johnson”, “9”, “male” and “140cm” “. We can access the corresponding value by key.

>>> person["name"]
>>> person["gender"]

But if the value is accessed with a key that is not in the dictionary, Python will output an error message like this:

>>> person["grade"]
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
KeyError: 'grade'

There is no “grade” key in the person dictionary, so Python will report a “Key Error” message.

It is also possible to use integer values ​​as dictionary keys, just as we use integer values ​​as list indices, but the integer value can be any number and does not have to be in order. For example, you can use 100, 105, and 8 as the index values ​​for the 3 elements, respectively.

Hint: The elements in a dictionary are not ordered, as shown below.

>> fruits={100:"apple",105:"banana",8:"orange"}
>> print(fruits)
{100: 'apple', 105: 'banana', 8: 'orange'}

We could also create an empty dictionary first and add each key-value pair row by row. Let’s see how to create a dictionary person in this way.

>>> person={}
>>> person["name"]="Johnson"
>>> person["age"]=9
>>> person["gender"]="male"
>>> person[" height"]="140cm"
>>> print(person)
{'name': 'Johnson', 'age': 9, 'gender': 'male', 'height': '140cm'}

The keys in the dictionary are unique. If there are duplicate keys, the following key-value pairs will replace the previous key-value pairs. However, the values ​​do not need to be unique, that is, different keys can have the same value.

>>> fruits={100:"apple",105:"banana",8:"orange",100:"cherry",200:"banana"}
>>> print(fruits)
{100: 'cherry', 105: 'banana', 8: 'orange', 200: 'banana'}

We see that the value corresponding to the key “100” is “cherry”, and the value “apple” has been overwritten. However, the keys “105” and “200” both correspond to the value “banana”, which is fine.

Python modify and add value in dictionary

The syntax for modifying a value in a dictionary is similar to the syntax for accessing a value in a dictionary. You need to specify the dictionary name and the key of the value to be modified, and then specify the new value to be associated with the key. Let’s take the person dictionary as an example, first assign a dictionary to the person variable.

>>> person={"name":"Johnson","age":9,"gender":"male","height":"140cm"}
>>> print(person)
{'name': 'Johnson ', 'age': 9, 'gender': 'male', 'height': '140cm'}

Now change the value for the key “age” from 9 to 8 and print out the dictionary person.

>>> person["age"]=8
>>> print(person)
{'name': 'Johnson', 'age': 8, 'gender': 'male', 'height': '140cm'}

We can see that the value for the key “age” in the dictionary person is now 8 instead of 9.

The way to add new content to a dictionary is to add new key-value pairs. For example, we want to add a new key “grade” to the person dictionary and assign the integer 3 to this key.

>>> person["grade"]=3
>>> print(person)
{'name': 'Johnson', 'age': 9, 'gender': 'male', 'height': '140cm', ' grade': 3}

By printing the person dictionary, we can see that new key-value pairs have been added to the dictionary.

Python delete key-value pair

For information that is no longer needed in the dictionary, we can use the del statement to delete it. When using the del statement, specify the dictionary name and the key to delete. Let’s take the person dictionary as an example, and this time delete the key-value pair with the key “age”.

>>> person={"name":"Johnson","age":9,"gender":"male","height":"140cm"}
>>> print(person)
{'name': 'Johnson ', 'age': 9, 'gender': 'male', 'height': '140cm'}
>>> del person["age"]
>>> print (person)
{'name': 'Johnson', 'gender': 'male', 'height': '140cm'}

As you can see, the key “age” and its corresponding value 9 have been removed from the dictionary person, and the other key-value pairs are not affected.

We can also use the dictionary’s clear() method to delete all key-value pairs in the dictionary. Let’s take the person dictionary as an example. After calling the clear() method, print the person dictionary again, and you can see that there is no more content in the dictionary.

>>> person.clear()
>>> print(person)

Python returns the value of the specified key

For a known key in the dictionary, you can use the get statement to return the value corresponding to the specified key, or return the default value if the key is not in the dictionary. Let’s also take the person dictionary as an example, this time to get the values ​​corresponding to the keys “name” and “weight”.

>>> person={"name":"Johnson","age":9,"gender":"male","height":"140cm"}
>>> print (person.get("name"))
>>> print (person.get("weight"))

It can be seen that the value corresponding to the key “name” is “Johnson”; the value of the key “weight” does not exist in the dictionary, so the system default value “None” is returned.

We can also specify a desired default value such as “unKnown”.

>>> print (person.get("weight","unKnown"))
unKnownThe default value returned this time is "unKnown", not "None".