Sometimes, we want to use Python dict.fromkeys without all values pointing to same list.
In this article, we’ll look at how to use Python dict.fromkeys without all values pointing to same list.
How to use Python dict.fromkeys without all values pointing to same list?
To use Python dict.fromkeys without all values pointing to same list, we can make a copy of the list with list
and use dictionary comprehension.
For instance, we write:
keys = ['a', 'b', 'c']
value = [0, 0]
d = {key: list(value) for key in keys}
print(d)
We call list
on value
to return a copy of value
for each entry.
And we use key
in keys
as the keys.
Therefore, d
is {'a': [0, 0], 'b': [0, 0], 'c': [0, 0]}
where [0, 0]
in each entry is different.
Conclusion
To use Python dict.fromkeys without all values pointing to same list, we can make a copy of the list with list
and use dictionary comprehension.