+4 votes
in Programming Languages by (77.2k points)
I want to select some key-value pair of a dictionary which is really big. Unlike list, dictionary does not have slice operation. How can I select a subset of the dictionary.

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

If you know the list of keys that you want to select for your sub_dictionary, you can try the following code. I have a dictionary 'f1' which has 7 keys and I am selecting just 3 keys in the subset.

>>> f1 = {'a':10,'b':11,'c':24,'d':15,'e':45,'f':23,'g':56}
>>> f1
{'a': 10, 'b': 11, 'c': 24, 'd': 15, 'e': 45, 'f': 23, 'g': 56}
>>> desired_key = ['a','f','g']
>>> subdict = {k:f1[k] for k in f1.keys() if k in desired_key}
>>> subdict
{'a': 10, 'f': 23, 'g': 56}
 


...