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

Usage in Python dictionary you must know

Nov 28, 2019 pm 05:12 PM
dictionary usage

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;
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]: {&#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
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]: {&#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
Copy after login

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;])
Copy after login

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;}
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]: {&#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;}
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)
{&#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 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=&#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]}
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 = [&#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}
Copy after login

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}
Copy after login

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}
Copy after login

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}
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: &#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;}
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 = {&#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}
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([(&#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
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 = [{&#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]
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 = {&#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)}
Copy after login

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}
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Analyze the usage and classification of JSP comments Analyze the usage and classification of JSP comments Feb 01, 2024 am 08:01 AM

Classification and Usage Analysis of JSP Comments JSP comments are divided into two types: single-line comments: ending with, only a single line of code can be commented. Multi-line comments: starting with /* and ending with */, you can comment multiple lines of code. Single-line comment example Multi-line comment example/**This is a multi-line comment*Can comment on multiple lines of code*/Usage of JSP comments JSP comments can be used to comment JSP code to make it easier to read

Python program to get first and last element in dictionary Python program to get first and last element in dictionary Sep 07, 2023 pm 05:01 PM

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Developed by GudioVanRossum in 1991. It supports multiple programming paradigms, including structured, object-oriented, and functional programming. Before we dive into this topic, let's review the basic concepts relevant to the questions we provide. A dictionary is a unique, mutable, and ordered set of items. Curly braces are used when writing dictionaries, and they contain keys and values: key names can be used to refer to dictionary objects. Data values ​​are stored in dictionaries in the form of key:value pairs. Ordered and unordered meaning When we say that a dictionary is ordered, we mean that its contents have a certain order and do not change. Unordered items lack a clear order and therefore cannot be used

Empty dictionary key incorrect: How to solve Python's dictionary key error? Empty dictionary key incorrect: How to solve Python's dictionary key error? Jun 24, 2023 pm 03:03 PM

The dictionary in Python is a flexible and powerful data structure that can store key-value pairs and has fast search and insertion functions. However, if you are not careful with dictionary key-value pairs, you may encounter the problem of empty dictionary keys. This problem often causes the code to crash or output unexpected results. This article will introduce two methods to solve the empty dictionary key error in Python. Method 1: Use if statements to prevent empty dictionary keys. Python dictionaries cannot have duplicate keys, otherwise the previous key-value pairs will be overwritten. When the value of a dictionary key is empty

How to get the next key in a dictionary in Python? How to get the next key in a dictionary in Python? Aug 28, 2023 pm 11:45 PM

Dictionaries are a powerful data type in Python. It consists of key-value pairs. Searching, appending and other operations can be efficiently completed through this data type. While accessing values ​​in a dictionary is simple, there may be situations where you need to look up the next key in the dictionary. Python provides several ways to achieve this, depending on your specific requirements. In this article, we will explore different ways of getting the next key in a dictionary in Python. Using the keys and index methods dictionaries are unordered collections in Python. So we first need to convert the keys into some sorted form. We can first append all keys in the form of a list. Next, we can find the next key by indexing the list. With the help of keys we can also

Usage of WPSdatedif function Usage of WPSdatedif function Feb 20, 2024 pm 10:27 PM

WPS is a commonly used office software suite, and the WPS table function is widely used for data processing and calculations. In the WPS table, there is a very useful function, the DATEDIF function, which is used to calculate the time difference between two dates. The DATEDIF function is the abbreviation of the English word DateDifference. Its syntax is as follows: DATEDIF(start_date,end_date,unit) where start_date represents the starting date.

How to correctly use the exit function in C language How to correctly use the exit function in C language Feb 18, 2024 pm 03:40 PM

How to use the exit function in C language requires specific code examples. In C language, we often need to terminate the execution of the program early in the program, or exit the program under certain conditions. C language provides the exit() function to implement this function. This article will introduce the usage of exit() function and provide corresponding code examples. The exit() function is a standard library function in C language and is included in the header file. Its function is to terminate the execution of the program, and can take an integer

Introduction to Python functions: Usage and examples of abs function Introduction to Python functions: Usage and examples of abs function Nov 03, 2023 pm 12:05 PM

Introduction to Python functions: usage and examples of the abs function 1. Introduction to the usage of the abs function In Python, the abs function is a built-in function used to calculate the absolute value of a given value. It can accept a numeric argument and return the absolute value of that number. The basic syntax of the abs function is as follows: abs(x) where x is the numerical parameter to calculate the absolute value, which can be an integer or a floating point number. 2. Examples of abs function Below we will show the usage of abs function through some specific examples: Example 1: Calculation

Introduction to Python functions: Usage and examples of isinstance function Introduction to Python functions: Usage and examples of isinstance function Nov 04, 2023 pm 03:15 PM

Introduction to Python functions: Usage and examples of the isinstance function Python is a powerful programming language that provides many built-in functions to make programming more convenient and efficient. One of the very useful built-in functions is the isinstance() function. This article will introduce the usage and examples of the isinstance function and provide specific code examples. The isinstance() function is used to determine whether an object is an instance of a specified class or type. The syntax of this function is as follows

See all articles