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!