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)

不言
不言forward
2018-10-23 16:11:492091browse
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)

Result:

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

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)

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}

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!

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