Python programming to extract the subset from the dictionary for analysis, python subset
This example describes how to extract a subset from a dictionary using Python programming. We will share this with you for your reference. The details are as follows:
First, we will consider usingDictionary Derivation)To solve this problem, for example:
Prices = {'acme ': 45.23, 'apple': 666, 'ibm': 343, 'hpq': 33, 'fb ': 10} # select gt200 = {key: value for key, value in prices. items () if value> 200} print (gt200) print ('---------------------') # extract information related to technology companies tech = {'apple', 'ibm ', 'hpq ', 'fb '} techDict = {key: value for key, value in prices. items () if key in tech} print (techDict)
The running result is as follows:
{'APPLE': 666, 'IBM': 343}---------------------{'APPLE': 666, 'FB': 10, 'IBM': 343, 'HPQ': 33}
Most problems that can be solved through dictionary derivation can also be solved throughCreate a sequence of tuplesAnd then pass themdict()
Function, for example:
gt200Dict=dict((key,value) for key,value in prices.items() if value > 200)print(gt200Dict)print('---------------------')techDict2={ key:prices[key] for key in prices.keys() & tech}print(techDict2)
However, for the first output result, the dictionary derivation scheme is clearer and runs faster. The second output is much slower, dictionary derivation is used as the best choice.