Home > Net >  How to convert list items to dictionary keys with 0 as default values?
How to convert list items to dictionary keys with 0 as default values?

Time:09-10

I'm trying to turn this list:

['USA', 'Canada', 'Japan']

into this dictionary:

{'USA': 0, 'Canada': 0, 'Japan': 0}

Can it be achieved with a simple loop? How would you go about it? Thanks!

CodePudding user response:

Use dict.fromkeys:

lst = ["USA", "Canada", "Japan"]

out = dict.fromkeys(lst, 0)
print(out)

Prints:

{'USA': 0, 'Canada': 0, 'Japan': 0}

CodePudding user response:

You can use collections.defaultdict, iteratevely appending keys to empty dictionaries:

class collections.defaultdict(default_factory=None, /[, ...])

Return a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable.

>>> from collections import defaultdict
>>> lst = ["USA", "Canada", "Japan"]
>>> new = defaultdict(dict)
>>> for x in lst:
...     new[x] = 0
...
>>> new
defaultdict(<class 'dict'>, {'USA': 0, 'Canada': 0, 'Japan': 0})
  • Related