Home > Backend Development > Python Tutorial > Python implements a method to extract subsets from a dictionary (code)

Python implements a method to extract subsets from a dictionary (code)

不言
Release: 2018-10-23 16:11:49
forward
2078 people have browsed it
The content of this article is about the method (code) of extracting subsets from the dictionary in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Requirements

We want to create a dictionary, which itself is a subset of another dictionary.

2. Solution

It can be easily solved using dictionary derivation.

prices={
'a':1.1,
'b':2.2,
'c':3.3,
'd':4.4,
'e':5.5
}
p1={key:value for key ,value in prices.items() if value>3}
print(p1)

names={'a','b'}
p2={key:value for key,value in prices.items() if key in names}
print(p2)
Copy after login

Result:

{'c': 3.3, 'd': 4.4, 'e': 5.5}
{'a': 1.1, 'b': 2.2}
Copy after login

3. Analysis

Most of the problems that can be solved by dictionary derivation can also be solved by creating a sequence of tuples and then They are passed to the dict() function to complete, for example:

#结果为:{'c': 3.3, 'd': 4.4, 'e': 5.5}
p3=dict((key,value) for key,value in prices.items() if value>3)
Copy after login

But the dictionary derivation method is clearer and actually runs much faster. (The first efficiency will be nearly 2 times faster)

Sometimes there are multiple ways to complete the same thing in the same time. For example, the second example can also be rewritten as:

#结果为:{'b': 2.2, 'a': 1.1}
p4={key:prices[key] for key in prices.keys() & names}
Copy after login

However, tests show that this solution is almost 1.6 times slower than the first one. Therefore, when there are multiple solutions to the same problem, you can do a little test to study the time spent.

The above is the detailed content of Python implements a method to extract subsets from a dictionary (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.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