In some of my previous articles we discussed the following dictionary methods:
– get
Feel free to read about them if you haven’t done so yet.
In this article we’ll be talking about another dictionary method, fromkeys.
Here’s the video version of this article:
The fromkeys(sequence[, value]) method creates a new dictionary with keys from sequence. If the optional parameter value is given, all the values are set to it. Here we’re using a list as the sequence:
>>> sequence = ["first name", "last name", "address"]
If the value parameter is not passed to the method, the values default to None:
>>> data_dictionary = dict.fromkeys(sequence)
>>> data_dictionary
{'first name': None, 'last name': None, 'address': None}
So let’s try setting the value in the method:
>>> data_dictionary = dict.fromkeys(sequence, "Top secret")
>>> data_dictionary
{'first name': 'Top secret', 'last name': 'Top secret', 'address': 'Top secret'}
Here’s how it looks with tuples:
>>> sequence = ("first name", "last name", "address")
>>> data_dictionary = dict.fromkeys(sequence, "Unknown")
>>> data_dictionary
{'first name': 'Unknown', 'last name': 'Unknown', 'address': 'Unknown'}
Also strings and ranges can be used:
>>> sequence = "ABC"
>>> data_dictionary = dict.fromkeys(sequence, "?")
>>> data_dictionary
{'A': '?', 'B': '?', 'C': '?'}
>>> sequence = range(4)
>>> data_dictionary = dict.fromkeys(sequence, 0)
>>> data_dictionary
{0: 0, 1: 0, 2: 0, 3: 0}