fromkeys() method in Python Dictionary

In this article, we would cover fromkeys() method in Python Dictionary. This method is particularly useful if we want to create a dictionary just using the keys with None values. Apart from that, we can use desired values too. As already discussed in earlier articles, a dictionary contains key:value pairs or items.

The following is the syntax for fromkeys() method

dictionary_name.fromkeys(key, value)

The value parameter is optional and if nothing is provided then it defaults to None.

We will cover more about fromkeys() with relevant examples next.

fromkeys() method in Python Dictionary

Example I. We first take how to create a dictionary by only using keys. Furthermore, the value is set to default i.e. None.

Let’s say we create a dictionary, x –

a = ('name', 'address', 'contact_num')
x = dict.fromkeys(a)

Now, use print() method to check –

print(x)

It would return with –

{'name': None, 'address': None, 'contact_num': None}

Clearly, we store the key data in variable a. And, a dictionary x was created through fromkeys() method. In the output, as expected it uses None in the values.

Example II. Moving forward, what if we want to use some data as value in place of None. There are many other ways to get this done. But, we declare an extra variable b, and assign following values to it –

b = ('ABC')
a = ('name', 'address', 'contact_num')
x = dict.fromkeys(a, b)
print(x)

The output should resemble –

{'name': 'ABC', 'address': 'ABC', 'contact_num': 'ABC'}

In the output, the data stored in variable b is used as value. And, it is used in place of default value – None. Rest of the code is same to that of Example I.

In conclusion, we have covered fromkeys() method in Python dictionary here.

Similar Posts