I have a dictionary:
{'key1':1, 'key2':2, 'key3':3}
I need to pass a sub-set of that dictionary to third-party code. It only wants a dictionary containing keys ['key1', 'key2', 'key99']
and if it gets another key (eg 'key3'
), it explodes in a nasty mess. The code in question is out of my control so I'm left in a position where I have to clean my dictionary.
What's the best, way to limit a dictionary to a set of keys?
Given the example dictionary and allowed keys above, I want:
{'key1':1, 'key2':2}
To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.
Both sets have one element: One has the key value tuple "name":"Girls" and the other has the single element composed of a key value tuple "show": {"name": "Girls"} and when two sets both have one element, those elements must be equal for the sets to be considered subsets of eachother.
Key Points to Remember:Slicing Nested Dictionary is not possible. We can shrink or grow nested dictionary as need. Like Dictionary, it also has key and value. Dictionary are accessed using key.
In [38]: adict={'key1':1, 'key2':2, 'key3':3} In [41]: dict((k,adict[k]) for k in ('key1','key2','key99') if k in adict) Out[41]: {'key1': 1, 'key2': 2}
In Python3 (or Python2.7 or later) you can do it with a dict-comprehension too:
>>> {k:adict[k] for k in ('key1','key2','key99') if k in adict} {'key2': 2, 'key1': 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With