Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove keys from object not in a list in python? [duplicate]

Tags:

python

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.

like image 436
Setsuna Avatar asked Sep 22 '15 21:09

Setsuna


People also ask

How do you get rid of duplicate keys in Python?

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.

How do I remove an object from a key in Python?

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.


1 Answers

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]
like image 102
phihag Avatar answered Oct 08 '22 11:10

phihag