114 – dict.fromkeys

114 – dict.fromkeys#

If you have an iterable of keys you can initialise a dictionary by using the class method dict.fromkeys, which creates a dictionary where all keys map to the value None:

keys = ["name", "age", "address"]
person_info = dict.fromkeys(keys)

print(person_info)
{
    'name': None,
    'age': None,
    'address': None,
}

If the default value None doesn’t suit you, you can change it by passing a different default value as the second argument to dict.fromkeys:

person_info = dict.fromkeys(keys, "")

print(person_info)
{
    'name': "",
    'age': "",
    'address': "",
}

Be careful when passing mutable values as the default value, though:

keys = ["a", "b", "c"]
my_dict = dict.fromkeys(keys, [])

my_dict["a"].append("Hello")
my_dict["b"].append("there")
print(my_dict["c"])  # ['Hello', 'there']

Further reading: