Usage in Python dictionary you must know

angryTom
Release: 2019-11-28 17:12:15
forward
2791 people have browsed it

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)
 in 
----> 1 print(dict_1['nama'])
KeyError: 'nama'
Copy after login

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]: {'name': None, 'age': 24, 'sex': None}
In [16]: print('name' in dict_1)
True
In [17]: print('nama' in dict_1)
False
Copy after login

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]: {'name': None, 'age': 24, 'sex': None}
In [19]: print(dict_1.items())
dict_items([('name', None), ('age', 24), ('sex', None)])
In [20]: for key, value in dict_1.items():
    ...:     print(key, value)
    ...:
name None
age 24
sex None
Copy after login

keys()

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

In [21]: dict_1
Out[21]: {'name': None, 'age': 24, 'sex': None}
In [22]: print(dict_1.keys())
dict_keys(['name', 'age', 'sex'])
Copy after login

values()

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

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

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]: {'name': None, 'age': 24, 'sex': None, 'sub_name': 'Tony'}
In [32]: dict_2
Out[32]: {'name': 'Mary', 'age': 18, 'sex': None, 'sub_name': ''}
In [33]: dict_1.update(dict_2)
In [34]: dict_1
Out[34]: {'name': 'Mary', 'age': 18, 'sex': None, 'sub_name': ''}
Copy after login

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)
{'name': 'Tony', 'age': 24}
In [4]: dict_2.clear()
In [5]: dict_2
Out[5]: {}
In [6]: dict_1
Out[6]: {}
Copy after login

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='Tony', info=['boy', 24])
In [2]: dict_3 = dict_1.copy()
In [3]: dict_3['name'] = "Ring"
In [4]: dict_3['info'].remove('boy')
In [5]: dict_3
Out[5]: {'name': 'Ring', 'info': [24]}
In [6]: dict_1
Out[6]: {'name': 'Tony', 'info': [24]}
Copy after login

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 = ['name', 'age', 'sex']
In [2]: dict_1 = dict.fromkeys(info)
In [3]: dict_1
Out[3]: {'name': None, 'age': None, 'sex': None}
Copy after login

Common operations

Merge dictionaries

There are four ways:

General processing

In [15]: dict_1
Out[15]: {'Tony': 24}
In [16]: dict_2
Out[16]: {'ben': 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]: {'Tony': 24, 'ben': 18}
Copy after login

update()

In [9]: dict_1
Out[9]: {'Tony': 24}
In [10]: dict_2
Out[10]: {'ben': 18}
In [12]: dict_3 = dict_1.copy()
In [13]: dict_3.update(dict_2)
In [14]: dict_3
Out[14]: {'Tony': 24, 'ben': 18}
Copy after login

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

In [33]: dict_1
Out[33]: {'Tony': 24}
In [34]: dict_2
Out[34]: {'ben': 18}
In [35]: dict_3 = dict(dict_1, **dict_2)
In [36]: dict_3
Out[36]: {'Tony': 24, 'ben': 18}
Copy after login

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: 'Tony', 18: 'ben'}
In [43]: dict_3
Out[43]: {'Tony': 24, 'ben': 18}
In [44]: dict_4 = {k:v for v, k in dict_3.items()}
In [45]: dict_4
Out[45]: {24: 'Tony', 18: 'ben'}
Copy after login

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 = {'Ben': 18, 'Jack': 12, 'Ring': 23, 'Tony': 24}
In [89]: b = {k:v for k, v in a.items() if v > 18}
In [90]: b
Out[90]: {'Ring': 23, 'Tony': 24}
Copy after login

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([('a', 2), ('b', 4), ('c', 5)])
In [51]: for key, value in ordered_dict.items():
    ...:     print(key, value)
    ...:
a 2
b 4
c 5
Copy after login

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 = [{'a': 1}, {'b': 3}, {'c': 4}, {'a':5}, {'b':2}, {'b': 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, {'a': [1, 5], 'b': [3, 2, 4], 'c': [4]})
In [69]: b['a']
Out[69]: [1, 5]
Copy after login

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 = {'a':1, 'b':2, 'c':3}
In [79]: b = {'b':3, 'c':3, 'd':4}
In [80]: a.keys() & b.keys()
Out[80]: {'b', 'c'}
In [81]: a.keys() - b.keys()
Out[81]: {'a'}
In [82]: a.items() & b.items()
Out[82]: {('c', 3)}
Copy after login

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

In [85]: a
Out[85]: {'a': 1, 'b': 2, 'c': 3}
In [86]: c = {k: a[key] for k in a.keys() - {'b'}}
In [87]: c
Out[87]: {'a': 3, 'c': 3}
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!