problem: construct a dictionary, which is a subset of another dictionary
Answer: The simplest way is to use a dictionary derivation
EG1:
1.
>>>prices = {' ACME ': 45.23, ' AAPL ': 612.78, ' IBM ': 205.55, ' HPQ ': 37.20, ' FB ': 10.75}
>>>P1 = {Key:value for key, value in Prices.items () if value > 200}
>>>p1
{' AAPL ': 612.78,' IBM ': 205.55}
2.
dictionary derivation can be done by creating a tuple sequence and then passing it to the dict () Letter number can also be achieved. For example:
>>>P1 = Dict ((key, value) for key, value in Prices.items () if value > 200)
However, the dictionary derivation is clearer and actually runs faster (in this case, the actual test is almost a whole lot faster than the dcit () function).
EG2:
1.
>>>tech_names = {' AAPL ', ' IBM ', ' HPQ ', ' MSFT '}
>>>P2 = {Key:value for key, value in Prices.items () if key in Tech_names}
{' AAPL ': 612.78, ' IBM ': 205.55, ' HPQ ': 37.20}
2.
>>>tech_names = {' AAPL ', ' IBM ', ' HPQ ', ' MSFT '}
>>>P2 = {Key:prices[key] for key in Prices.keys () & Tech_names}
However, the run-time test results show that this scenario is about 1.6 times times slower than the first scenario. If the performance requirements of the program are relatively high, it will take some time to do the timing test.
Python: Extracting a subset from a dictionary--dictionary derivation