Home >Backend Development >Python Tutorial >Usage in Python dictionary you must know

Usage in Python dictionary you must know

angryTom
angryTomforward
2019-11-28 17:12:152983browse

The Python version of this article is 3.7.X. Before reading this article, you need to understand the basic usage of python dictionary.

Usage in Python dictionary you must know

Introduction

The dictionary (dict) is a built-in data structure in Python, consisting of multiple key-value pairs. (key) and value (value) are separated by colons, each key-value pair is separated by commas (,), the entire dictionary is included in curly brackets ({}), the key must be unique, and the value can be of any type. But the keys must be of immutable type like string, number or tuple.

Recommended: "python tutorial"

The bottom layer uses a hash table to associate keys And value,dict is unordered. Features include:

● The search and insertion speed is extremely fast and will not slow down as the number of keys increases;

● It requires more memory

So, dict is a data structure that trades space for time and is used in scenarios where fast search is required.

Operation: Common methods

get()

Return the value of the specified key. If the key does not exist, return the default value (default is None ) without reporting an error, the syntax is dict.get(key).

dict_1['age'] = 24
In [7]: print(dict_1.get('age'))
24
In [11]: print(dict_1.get('nama'))
None
In [12]: print(dict_1['nama'])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-12-ef61a380920e> in <module>
----> 1 print(dict_1[&#39;nama&#39;])
KeyError: &#39;nama&#39;

key in dict

Use the in operator to determine whether the key exists in the dictionary. If it exists, it returns True, otherwise it returns False. The syntax is: key in dict .

In [15]: dict_1
Out[15]: {&#39;name&#39;: None, &#39;age&#39;: 24, &#39;sex&#39;: None}
In [16]: print(&#39;name&#39; in dict_1)
True
In [17]: print(&#39;nama&#39; in dict_1)
False

In python 2, this function is implemented using the has_key() method.

items()

Returns a traversable (key, value) tuple array in list form, the syntax is dict.items().

In [18]: dict_1
Out[18]: {&#39;name&#39;: None, &#39;age&#39;: 24, &#39;sex&#39;: None}
In [19]: print(dict_1.items())
dict_items([(&#39;name&#39;, None), (&#39;age&#39;, 24), (&#39;sex&#39;, None)])
In [20]: for key, value in dict_1.items():
    ...:     print(key, value)
    ...:
name None
age 24
sex None

keys()

Returns all keys of a dictionary as a list: dict.keys()

In [21]: dict_1
Out[21]: {&#39;name&#39;: None, &#39;age&#39;: 24, &#39;sex&#39;: None}
In [22]: print(dict_1.keys())
dict_keys([&#39;name&#39;, &#39;age&#39;, &#39;sex&#39;])

values()

Return all values ​​in the dictionary in list form: dict.values()

In [27]: dict_1
Out[27]: {&#39;name&#39;: None, &#39;age&#39;: 24, &#39;sex&#39;: None, &#39;sub_name&#39;: &#39;Tony&#39;}
In [28]: print(dict_1.values())
dict_values([None, 24, None, &#39;Tony&#39;])
setdefault()
和get()类似,用户获得与给顶尖相关联的值,不同的是,该方法如果键不存在时会添加键并将值设为默认值,语法为:dict.setdefault(key, default=None)。
In [23]: dict_1
Out[23]: {&#39;name&#39;: None, &#39;age&#39;: 24, &#39;sex&#39;: None}
In [24]: print(dict_1.setdefault(&#39;name&#39;))
None
In [25]: print(dict_1.setdefault(&#39;name&#39;, &#39;Tony&#39;))
None
In [26]: print(dict_1.setdefault(&#39;sub_name&#39;, &#39;Tony&#39;))
Tony
In [27]: dict_1
Out[27]: {&#39;name&#39;: None, &#39;age&#39;: 24, &#39;sex&#39;: None, &#39;sub_name&#39;: &#39;Tony&#39;}

update()

The syntax is: dict_1. update(dict_2) is used to update the key-value pairs of dict_2 to dict_1. If there are the same keys, they will be overwritten.

In [31]: dict_1
Out[31]: {&#39;name&#39;: None, &#39;age&#39;: 24, &#39;sex&#39;: None, &#39;sub_name&#39;: &#39;Tony&#39;}
In [32]: dict_2
Out[32]: {&#39;name&#39;: &#39;Mary&#39;, &#39;age&#39;: 18, &#39;sex&#39;: None, &#39;sub_name&#39;: &#39;&#39;}
In [33]: dict_1.update(dict_2)
In [34]: dict_1
Out[34]: {&#39;name&#39;: &#39;Mary&#39;, &#39;age&#39;: 18, &#39;sex&#39;: None, &#39;sub_name&#39;: &#39;&#39;}

clear()

Delete all items in the dictionary, dict.clear(), for example:

In [1]: dict_1 = dict(name="Tony", age=24)
In [2]: dict_2 = dict_1
In [3]: print(dict_2)
{&#39;name&#39;: &#39;Tony&#39;, &#39;age&#39;: 24}
In [4]: dict_2.clear()
In [5]: dict_2
Out[5]: {}
In [6]: dict_1
Out[6]: {}

copy ()

Shallow copy of the original dictionary, returning a new dictionary with the same key-value pairs, dict.copy(), for example:

In [1]: dict_1 = dict(name=&#39;Tony&#39;, info=[&#39;boy&#39;, 24])
In [2]: dict_3 = dict_1.copy()
In [3]: dict_3[&#39;name&#39;] = "Ring"
In [4]: dict_3[&#39;info&#39;].remove(&#39;boy&#39;)
In [5]: dict_3
Out[5]: {&#39;name&#39;: &#39;Ring&#39;, &#39;info&#39;: [24]}
In [6]: dict_1
Out[6]: {&#39;name&#39;: &#39;Tony&#39;, &#39;info&#39;: [24]}

fromkeys()

Create a new dictionary, dict.fromkeys(seq[, value]), using the elements in the sequence seq as the keys of the dictionary, and value is the initial value corresponding to all keys in the dictionary, where value is the Select parameters, default is None. Suitable for data initialization, for example:

In [1]: info = [&#39;name&#39;, &#39;age&#39;, &#39;sex&#39;]
In [2]: dict_1 = dict.fromkeys(info)
In [3]: dict_1
Out[3]: {&#39;name&#39;: None, &#39;age&#39;: None, &#39;sex&#39;: None}

Common operations

Merge dictionaries

There are four ways:

General processing

In [15]: dict_1
Out[15]: {&#39;Tony&#39;: 24}
In [16]: dict_2
Out[16]: {&#39;ben&#39;: 18}
In [17]: dict3 = dict()
In [18]: for key, value in dict_1.items():
    ...:     dict_3[key] = value
    ...:
In [19]: for key, value in dict_2.items():
    ...:     dict_3[key] = value
    ...:
In [20]: dict_3
Out[20]: {&#39;Tony&#39;: 24, &#39;ben&#39;: 18}

update()

In [9]: dict_1
Out[9]: {&#39;Tony&#39;: 24}
In [10]: dict_2
Out[10]: {&#39;ben&#39;: 18}
In [12]: dict_3 = dict_1.copy()
In [13]: dict_3.update(dict_2)
In [14]: dict_3
Out[14]: {&#39;Tony&#39;: 24, &#39;ben&#39;: 18}

Dict(d1, **d2) with the help of dictionary Method

In [33]: dict_1
Out[33]: {&#39;Tony&#39;: 24}
In [34]: dict_2
Out[34]: {&#39;ben&#39;: 18}
In [35]: dict_3 = dict(dict_1, **dict_2)
In [36]: dict_3
Out[36]: {&#39;Tony&#39;: 24, &#39;ben&#39;: 18}

Advanced

Dictionary derivation

is similar to list derivation, with the advantage of being used at the bottom level C implementation will be much faster and is recommended.

Swap the key values ​​of a dictionary

Use dictionary comprehensions to easily swap the key values ​​of a dictionary:

In [42]: dict_4
Out[42]: {24: &#39;Tony&#39;, 18: &#39;ben&#39;}
In [43]: dict_3
Out[43]: {&#39;Tony&#39;: 24, &#39;ben&#39;: 18}
In [44]: dict_4 = {k:v for v, k in dict_3.items()}
In [45]: dict_4
Out[45]: {24: &#39;Tony&#39;, 18: &#39;ben&#39;}

From the dictionary Extracting subsets from

I want to create a dictionary that is itself a subset of another dictionary.

For example:

In [88]: a = {&#39;Ben&#39;: 18, &#39;Jack&#39;: 12, &#39;Ring&#39;: 23, &#39;Tony&#39;: 24}
In [89]: b = {k:v for k, v in a.items() if v > 18}
In [90]: b
Out[90]: {&#39;Ring&#39;: 23, &#39;Tony&#39;: 24}

Generate an ordered dictionary

Dictionaries before Python3.6 are unordered, but sometimes we need To maintain the orderliness of the dictionary, orderDict can achieve the orderliness of the dictionary on the basis of dict. Order here refers to arranging it in the order in which the dictionary keys are inserted. This achieves a first-in-first-out dict. When the capacity When the limit is exceeded, the earliest added key is deleted first.

Example:

In [49]: from collections import OrderedDict
In [50]: ordered_dict = OrderedDict([(&#39;a&#39;, 2), (&#39;b&#39;, 4), (&#39;c&#39;, 5)])
In [51]: for key, value in ordered_dict.items():
    ...:     print(key, value)
    ...:
a 2
b 4
c 5

You can see that OrderedDict is sorted according to the insertion order when the dictionary is created.

Principle: OrderedDict internally maintains a doubly linked list, which arranges the key positions according to the order in which elements are added. This also results in the size of OrderedDict being more than twice that of an ordinary dictionary.

Merge dictionaries with the same key in the list

That is to generate the so-called one-key multi-value dictionary, the corresponding multiple values ​​need to be saved in other containers such as lists or Collection, depending on whether multiple values ​​need to be unique.

For example:

In [64]: from collections import defaultdict
In [65]: a = [{&#39;a&#39;: 1}, {&#39;b&#39;: 3}, {&#39;c&#39;: 4}, {&#39;a&#39;:5}, {&#39;b&#39;:2}, {&#39;b&#39;: 4}]
In [66]: b = defaultdict(list)
In [67]: [b[k].append(v) for item in a for k, v in item.items()]
Out[67]: [None, None, None, None, None, None]
In [68]: b
Out[68]: defaultdict(list, {&#39;a&#39;: [1, 5], &#39;b&#39;: [3, 2, 4], &#39;c&#39;: [4]})
In [69]: b[&#39;a&#39;]
Out[69]: [1, 5]

Find the similarities and differences between two dictionaries

Scenario: Find the similarities and differences between two dictionaries, including the same key or same value.

Analysis: A dictionary is a mapping set between a series of key values. It has the following characteristics:

keys() will return all keys in the dictionary, and the keys of the dictionary support set operations. , so the keys of the dictionary can be processed using the intersection and complement of sets;

items() returns an object composed of (key, value), supporting set operations;

values() and Set operations are not supported because there is no guarantee that all values ​​are unique, but if a judgment operation is necessary, the values ​​can be converted into sets first.

Example:

In [78]: a = {&#39;a&#39;:1, &#39;b&#39;:2, &#39;c&#39;:3}
In [79]: b = {&#39;b&#39;:3, &#39;c&#39;:3, &#39;d&#39;:4}
In [80]: a.keys() & b.keys()
Out[80]: {&#39;b&#39;, &#39;c&#39;}
In [81]: a.keys() - b.keys()
Out[81]: {&#39;a&#39;}
In [82]: a.items() & b.items()
Out[82]: {(&#39;c&#39;, 3)}

Another example, when creating a dictionary, it is expected that certain keys can be removed:

In [85]: a
Out[85]: {&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}
In [86]: c = {k: a[key] for k in a.keys() - {&#39;b&#39;}}
In [87]: c
Out[87]: {&#39;a&#39;: 3, &#39;c&#39;: 3}

This article comes from python tutorial Column, welcome to learn!

The above is the detailed content of Usage in Python dictionary you must know. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete