creating a dictionary from an old one by only duplicating the keys

Viewed 75

I'm wondering how can do create a kind of key_duplicated dictionary given a previously defined dictionary?

namely, Suppose we have a dictionary like this {"qq":1,"ww":2,"ee",3} then I want a new dictionary with the same keys and maybe some random values of the same type as the given dictionary {"qq":0,"ww":0,"ee":0}.

2 Answers

this one is very pythonic (also, it may be faster than dict comprehension).

d2 = dict.fromkeys(d1, 0)

You can use a dict comprehension:

d1 = {"qq":1,"ww":2,"ee": 3}
d2 = {k: 0 for k in d1}
Related