Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading