Thefromkeys()
method of dict
type is used to create a new dictionary with keys from a given iterable and values pre-filled with a specified default value.
The syntax is as shown below:
dict.setdefault(iterable, value = None)
The items in the created dictionary has the elements from the iterable
as keys and the specified value
as the default value. If value
is not given, None
will be used.
keys = [1, 2, 3, 4, 5]
d = dict.fromkeys(keys)
print(d)
If the default value is given, the item's values will be populated with the value instead of None
.
keys = ['one', 'two', 'three', 'four', 'five']
d = dict.fromkeys(keys, 0)
print(d)
In the above example, we specified 0
as the default value to thefromkeys()
method.
Note that the iterable argument can be any valid iterable not just lists. In the following example we use a range() for the iterable argument.
d = dict.fromkeys(range(5))
print(d)
Top comments (0)