3

im trying to exclude some key when passing a dict to a variable. for example.

dict1 = {
    'id': 1,
    'name' : 'John Woe',
    'flag' : True,
    'position' : 'Developer'
}

Now i would like to exclude the key flag or any specified keys when passing it to dict2 variable. Normally i can simple hardcodedly assign it but i want a dynamic approach.

Such as this:

dict2 = dict1.exclude(['flag', 'position'])
Shift 'n Tab
  • 8,808
  • 12
  • 73
  • 117

1 Answers1

5
keys_to_exclude = set(('flag',))
dict2 = {k:v for k,v in dict1.iteritems() if k not in keys_to_exclude}

As a response to the criticism in the comments about this being O(MN) - keys_to_exclude can be a set and it will make it O(N) with less burden to garbage collection, compared to copy/pop solution.

khachik
  • 28,112
  • 9
  • 59
  • 94