Skip to content Skip to sidebar Skip to footer

List Comprehension In A Dict.fromkeys(seta, ...)

I want to generate a new dictionary using pre-existing information. Using dict.fromkeys() passing arguments such as a set() of DictA.keys() and the DictA.values(), but, here's what

Solution 1:

That's because dict.fromkeys() reuses the second argument for all values. You stored the same list as a reference over and over again.

Use a dict comprehension instead:

{k: DictA.values() for k in DictA}

The left-hand side key and value expressions in a dict comprehension are executed for every iteration. Each time DictA.values() is called again, producing a new list object.

Note that there is no need to call set(DictA) here, you can iterate over DictAdirectly for all the keys, and they are already unique (they have to be).

Solution 2:

also consider using dict comprehension to modify the current dict like:

{k:v+data for k,v in DictA.items()}

or just:

d = {}
for k,v in DictA.items():
    d[k] = manipulate(v)

Post a Comment for "List Comprehension In A Dict.fromkeys(seta, ...)"