Home  >  Article  >  Backend Development  >  What are the basic operations of python dictionary?

What are the basic operations of python dictionary?

尚
Original
2020-01-15 10:25:2714776browse

What are the basic operations of python dictionary?

Dictionary is one of the five basic data types in Python. Although its assignment is a little more troublesome, it is really convenient to use. It uses key-value pairs to store data. The so-called key-value pair is a key that corresponds to a value. If the previous key is assigned a value again later, the first value will be overwritten.

1: Creation of dictionary

We know that lists in Python are represented by '[]', ancestors are represented by '()', and dictionaries are represented by '{ }' means that it is more troublesome to create than lists, tuples, and strings, but as long as you remember these three words of key value, you can create a dictionary type variable correctly. See the code below

d = {'a': '我是a', 'b': 1, 'c': [1, 2, 3], 'd': (1, 2, 3)}

print(d)
print(type(d))
print(d['a'])
print(d['c'][1])
print(d['d'][1])

The output results are as follows:

{'a': 'I am a', 'b': 1, 'c': [1, 2, 3], 'd': (1, 2, 3)}
7f7a529d7c829355be039cf711e6e765
I am a
2

In the first line we create a dictionary type called d. , we print each key name in English quotes, and the key value can be any data type. For example, the key value of the key a is a string, the part-time value of the key b is a number, and the key value of the key c is List, the key value of the key d is a tuple

The third line, output the entire dictionary, see if it looks exactly the same as when we created it,

The fourth line, use type The function checks the data type of the variable d and outputs dict. Yes, dict represents a dictionary, just like list represents a list.

In the fifth line, the value outputs the key value of the key a in the dictionary.

The sixth line, output the second element in the key value c. The key value of c is a list type, so we can operate d['c'] like a list

Seventh flight , similar to the sixth line, except that the key value type is replaced by the ancestor

2: Modify the dictionary

When creating the dictionary, we specify for each key What if we want to modify the key value of this key later? It is also very simple. You only need to reassign the key, as follows:

d = {'a': '我是a', 'b': 1, 'c': [1, 2, 3], 'd': (1, 2, 3)}


print(d['a'])
d['a'] = '我是被修改后的a'
print(d['a'])

The output result is as follows:

I am a
I am the modified a

On the fourth line we output the original key value of a, on the fifth line we modify the key value of a, and on the sixth line we output the modified key value of a

3: Deletion of dictionary

If we want to delete a key in the dictionary or the entire dictionary after creating a dictionary, we can use the del method.

d = {'a': '我是a', 'b': 1, 'c': [1, 2, 3], 'd': (1, 2, 3)}


print(d['a'])
del d['a']
print(d['a'])

The output is as follows

I am a
Traceback (most recent call last):
File "E:/py project/Miscellaneous example/dict_demo.py", line 8, in 4225fa317875f3e92281a7b1a5733569
print(d['a'])
KeyError: 'a'

On the fourth line above, we first output the key value of a , later use del to delete the key a, and access the key a again in the sixth line, an error will be reported KeyError: 'a'

What if we want to delete the entire dictionary at once? It is also very simple. Just modify the code on the fifth line slightly, delete ['a'] after d, and directly follow the dictionary name after del.

You can also use the pop() method of the dictionary to delete the del method. There is no return value when deleting. Pop will return the key value of the deleted key. If the key does not exist, you can also return the specified The error message is as follows:

d = {'a': '我是a', 'b': 1, 'c': [1, 2, 3], 'd': (1, 2, 3)}

print(d['a'])
print(d.pop('a', '123456'))
print(d.pop('e', '这个键不存在,无法删除'))

输入结果如下:
我是a
我是a
这个键不存在,无法删除

The third line outputs the value of key a

The fourth line deletes key a and returns the value of key a, because this key exists in the dictionary. So the following '123456'

The fifth line deletes the e key, and this key does not exist in the dictionary, so the following error message 'This key does not exist and cannot be deleted'

## is returned

#4: Clearing the dictionary

Sometimes, what we want to delete is not the entire dictionary, but just the contents of the dictionary. At this time, we can use the clear method of the dictionary to To clear the dictionary, the operation is as follows

d = {'a': '我是a', 'b': 1, 'c': [1, 2, 3], 'd': (1, 2, 3)}

d.clear()
print(d)

输出如下:
{}

It can be seen that d has become an empty dictionary at this time

5:.get method access key

Although the dictionary ['key name'] method is very convenient to access a key in the dictionary, it also has some shortcomings. If the key does not exist, the program will terminate, hindering the normal operation of the program. If you want Return the correct error message and allow the program to continue running. You can use the .get method to access the keys in the dictionary.

d = {'a': '我是a', 'b': 1, 'c': [1, 2, 3], 'd': (1, 2, 3)}

print(d.get('e', '这个键不存在'))
print(d['e'])

输入如下:
这个键不存在
Traceback (most recent call last):
  File "E:/py project/杂例/dict_demo.py", line 6, in <module>
    print(d[&#39;e&#39;])
KeyError: &#39;e&#39;

The third and fourth lines all access a key that does not exist in the dictionary, and The third line is accessed using the .get method and the set error message is returned. The program continues to run downwards. The fourth line is accessed using the normal method. The program reports an error and terminates.

6: in operator

In the dictionary, we can use the in operator to determine whether the key exists in the dictionary. If the key is in the dictionary dict, it returns true, otherwise it returns false. Look at the following simple code

d = {&#39;a&#39;: &#39;我是a&#39;, &#39;b&#39;: 1, &#39;c&#39;: [1, 2, 3], &#39;d&#39;: (1, 2, 3)}


print(&#39;a&#39; in d)
print(&#39;e&#39; in d)

The output result is as follows:

True

False

The fourth line, the key 'a' is in the dictionary , returns True, the fifth line, the key ''e is not in the dictionary, returns false

7:获取字典中键值对

现在我们已经知道,字典是以键值对(键和它对应的键值)的形式存储数据的,那么有没有什么方法让我们一次性获取一个字典中所有的键值对呢?可以用items()方法

字典的 items() 方法以列表返回可遍历的(键, 值) 元组数组。意思就是返回一个列表,列表里面的每个元素都是元组,一个元祖就是字典里面的一对键值对。

d = {&#39;a&#39;: &#39;我是a&#39;, &#39;b&#39;: 1, &#39;c&#39;: [1, 2, 3], &#39;d&#39;: (1, 2, 3)}

print(d.items())

for i, j in d.items():
    print(i, j)

输出结果如下:

dict_items([('a', '我是a'), ('b', 1), ('c', [1, 2, 3]), ('d', (1, 2, 3))])
a 我是a
b 1
c [1, 2, 3]
d (1, 2, 3)

第三行,我们输出了items()的返回结果,可以清楚的看到每个元祖都是字典里面的一个键值对,可以使用list把它转换为一个列表,能帮助我们更好的访问里面的元素。

第五行,利用items()方法帮助我们遍历一个字典,每次输出一个键和它对应的键值。

8:获取键

items()方法可以帮助我们一次性获取所有的键值对,但如果我们只想要获取键呢?可以使用 keys() 方法

d = {&#39;a&#39;: &#39;我是a&#39;, &#39;b&#39;: 1, &#39;c&#39;: [1, 2, 3], &#39;d&#39;: (1, 2, 3)}

print(d.keys())
l = list(d.keys())
print(l)
print(l[1])

输出结果如下:

dict_keys(['a', 'b', 'c', 'd'])
['a', 'b', 'c', 'd']
b

第三行的返回结果中,只有键,第四行把返回结果转换成了列表,第五行对这个列表进行输出,第六行输出列表中党的第二个元素,也就是字典的第二个键

9:获取值

既然能值获取到字典中的键,当然也能只获取字典中的字。就是values()方法

d = {&#39;a&#39;: &#39;我是a&#39;, &#39;b&#39;: 1, &#39;c&#39;: [1, 2, 3], &#39;d&#39;: (1, 2, 3)}

print(d.values())
l = list(d.values())
print(l)
print(l[1])

输出结果如下:

dict_values(['我是a', 1, [1, 2, 3], (1, 2, 3)])
['我是a', 1, [1, 2, 3], (1, 2, 3)]

与keys方法类似,只不过返回结果是字典中所有的键值而已。

python学习网,免费的在线学习python平台,欢迎关注!

The above is the detailed content of What are the basic operations of python dictionary?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn