Home > other >  How can I find which keys are absent from a Python dict?
How can I find which keys are absent from a Python dict?

Time:07-18

d is a Python dict mapping (some of) the integers in range(x) to values. How can I find which integers in that range are not mapped, and set them to a default value?

I do not want to just the dict's default, because I want the missing ints to appear in d.items().

CodePudding user response:

Iterate over the range and setdefault each key:

for i in range(x):
    d.setdefault(i, 42)

Note that setdefault sets a default value for that key (not the whole dictionary), if and only if that key isn't already set to something else.

You could also use a comprehension with get and a default value to build a new dictionary and assign it to d:

d = {i: d.get(i, 42) for i in range(x)}

CodePudding user response:

dict.keys() works much like a set and can even be used with range. Applying XOR works

>>> d = {1:1, 2:2, 3:3}
>>> d.update((k, None) for k in (d.keys() ^ range(10)))
>>> d
{1: 1, 2: 2, 3: 3, 0: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}

CodePudding user response:

A simple, though perhaps inefficient method, might be the following where ‘x’ defines the range and ‘42’ the default value:

for i in range(x):
    d[i] = d.get(i, 42) 
  • Related