I have these keys:
keep = ["a","c"]
My dict:
testdict = {'
'a':'vala',
'b':'valb',
'c':'valc',
'd':'vald'
}
Desired output:
testdict = {
'a':'vala',
'c':'valc'
}
I want to remove all keys that do not match the key in the list. What is the fastest way to do this?
I tried:
for key, value in testdict.iteritems():
if key not in keep:
del testdict[key]
But the above gives me errors since the size is changing.
You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set. You must convert the dictionary or set back into a list to see a list whose duplicates have been removed.
To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.
Instead of removing, simply construct a new dict:
newdict = {k: testdict[k] for k in keep}
If keep
can contain keys that are not present in testdict, add the appropriate condition:
newdict = {k: testdict[k] for k in keep if k in testdict}
If you absolutely must modify the dict object, bear in mind that you can not modify a dictionary while you're traversing over it. So traverse first and delete afterwards:
to_delete = set(testdict.keys()).difference(keep)
for d in to_delete:
del testdict[d]
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