Problem: Want to create a dictionary, which is itself a subset of another dictionary
Solution: Use dictionary derivation (dictionary comprehension) to easily solve
#example of extracting a subset from a dictionary fromPprintImportpprintprices= { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75}#Make A dictionary of pricesP1 = {Key:value forKey, ValueinchPrices.items ()ifValue > 200 }Print("All prices") Pprint (p1)#Make A dictionary of tech stocksTech_names = {'AAPL','IBM','HPQ','MSFT'}P2= {Key:value forKey,valueinchPrices.items ()ifKeyinchTech_names}Print("All Techs") Pprint (p2)
>>> ================================ RESTART ================================>>>200 {'AAPL'IBM': 205.55}all techs{' AAPL'HPQ'IBM': 205.55}
The dictionary-derived scheme is clear and fast to run.
"Python Cookbook" "Data Structure and algorithm" 16. Extracting subsets from a dictionary