Python tip 8: dict.fromkeys() method
A lesser known way to create a dictionary is to use the fromkeys()
method that accepts an iterable and an optional value (default is None
). The same value will be assigned to all the keys, so be careful if you want to use a mutable object.
>>> colors = ('red', 'blue', 'green')
>>> dict.fromkeys(colors)
{'red': None, 'blue': None, 'green': None}
>>> dict.fromkeys(colors, 255)
{'red': 255, 'blue': 255, 'green': 255}
When you iterate over a dictionary object, you'll get only the keys. For example:
>>> fruits = {'banana': 12, 'papaya': 5, 'mango': 10}
>>> for fruit in fruits:
... print(fruit)
...
banana
papaya
mango
Recent Python versions ensure that the insertion order is maintained for a dictionary. So, you can remove duplicate items from a list while maintaining the order by building a dictionary using the fromkeys()
method and converting it back to a list.
>>> nums = [1, 4, 6, 22, 3, 5, 4, 3, 6, 2, 1, 51, 3, 1]
# remove duplicates, if you don't care about the element order
>>> list(set(nums))
[1, 2, 3, 4, 5, 6, 51, 22]
# remove duplicates, if you want to maintain the element order
>>> list(dict.fromkeys(nums))
[1, 4, 6, 22, 3, 5, 2, 51]
Video demo:
See also my 100 Page Python Intro ebook.