Python Dictionary fromkeys() Method

Python Dictionary Fromkeys() Method

This is a detailed tutorial of the Python Dictionary fromkeys() method. Learn to create new dictionaries using keys from a given sequence & value.

Python Dictionary fromkeys()

The dict.fromkeys() method is used to create a new dictionary from a given sequence of keys and a defined value by the user. Unlike most of the other Python Dictionary methods, you actually need not apply this method on any defined dictionary or empty dictionary, rather this method will create a dictionary for you by applying it on a new dict object keyword.

Syntax

The following syntax creates a new dictionary named newDict that will get its keys from the given sequence keys and the value for all the keys will be the same which will be defined as the value argument.

fromkeys() Parameters

As shown in the syntax, the method fromkeys() takes two arguments. The first argument keys is a sequence that contains the keys of the dictionary to be generated. This sequence could be in the form of any collection object like List, Tuple, or Set. Further, the sequence may contain keys of any data type. This argument is mandatory to be passed.

The second argument value is the actual value that you want to assign to all of the keys in the dictionary to be generated. This is an optional argument and if you will not pass this argument, all the keys will be assigned the default value None.

fromkeys() Return Value

This method returns a new dictionary that will contain all of the keys as you passed as a sequence in the first argument and the value assigned to these keys will be the value passed in the second argument or will be None, if you did not pass the second argument. You can give reference to this returned dictionary using a new variable as I’ve illustrated in the syntax.

Examples

Different sort of examples are given below to help you have a clear idea about the usage of the Python Dictionary fromkeys() method.

Example 1. Generating a dictionary only from a given sequence of Keys

In the following code snippet, I’ve simply defined a Python List named keys containing the sequence of the keys to be used for the dictionary to generated using the fromkeys() method.


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]
#Creating a new Dictionary from Keys Sequence
bio = dict.fromkeys(keys)


print(bio)


As you can see, I’ve not passed the optional parameter value as the argument here and hence it creates a new dictionary from the given keys but all of these keys have their assigned values as None.

Output.

Example 2. Creating a dictionary from a given sequence of Keys & a fixed Value

The only difference in this example from the first one is that here I’ve also passed the value as the second argument to the fromkeys() method.


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]
#value to be assigned to each of dictionary key item
value = "Hello"


#Creating a new Dictionary from Keys Sequence
bio = dict.fromkeys(keys, value)


print(bio)


As you can observe in the output, now the dictionary contains the same defined value for all of its keys.

Output.

Example 3. Change in Dictionary if Value is a Mutable Object

In case, you’re making use of a mutable object (The objects whose values can be changed) as the value argument for the Python Dictionary fromkeys() method, then you must know the fact that any change in the mutable object, will also result in a change in the generated dictionary key values.

Have a look at the following example to understand this concept.


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]
#value to be assigned to each of dictionary key item
value = ["Hello",True]
#Creating a new Dictionary from Keys Sequence
bio = dict.fromkeys(keys, value)


print("Before Change in Value:", bio)


value.clear()


print("After Change in Value:", bio)


Here the value argument is actually a list object and as you know, the list is a mutable object i.e. its items can be changed or removed. As you can see, we’ve applied the Python List clear() method on the value and it removes all of the list items. Due to this, the value of the keys in the dictionary is also reflecting the change. Now, all the key item values are also empty lists.

Therefore, the conclusion is if the value argument of the fromkeys() method is a mutable object, then the change in the items of the mutable object will also result in a change in the value of the dictionary key values.

Output.

If you do not want this thing to happen, you have two alternatives, either you can use the copy() method to create a copy of the mutable object to be passed as the argument to the fromkeys() method or you can simply follow the concept of dictionary comprehension to generate a new dictionary as the alternative to the dict.fromkeys() method.

But even in the Dictionary method, either you have to provide a copy of the sequence. You can provide a copy of the sequence, either by applying the copy() method again or by using the built-in function list to simply create a new sequence object. You’ll have a clear idea about this after understanding the Example 5.

Example 4. Avoid Change in Dictionary For Mutable Object Value

This example illustrates the use copy() method to avoid the changes happening to the dictionary key item values if a change occurs in the mutable sequence object that is passed as the value argument to the fromkeys() method.


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]
#value to be assigned to each of dictionary key item
value = ["Hello",True]
#Creating a new Dictionary from Keys Sequence
#Using the copy() method
bio = dict.fromkeys(keys, value.copy())


print("Before Change in Value:", bio)


#Clearing the value mutable object
value.clear()


print("After Change in Value:", bio)


We’ve made a very small change in this code. Instead of passing the variable value directly as the argument, we’re applying the copy() method on the variable value and then passing it. This will pass a different copy of the original list and hence making changes in the original list will not reflect any change in the dictionary so created using the fromkeys() method.

Output.

Example 5. Generate Dictionaries using Comprehension Method

Dictionary Comprehension is an alternative way to dynamically generate dictionaries using a given sequence of keys and a fixed value. Two code snippets are given below. In the first snippet, we’re not creating the list copy and in the second snippet, we’re doing so by applying the built-in function list().

Case 1.


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]
value = [1, 2, 3]
#Creating a new Dictionary using Comprehension
bio = { key : value for key in keys }


print("Before Change in Value:", bio)


value.clear()


print("After Change in Value:", bio)


Output.

Case 2.


#Defined Sequence of Keys
keys = ["name", "gender", "age", "website"]
value = [1, 2, 3]
#Creating a new Dictionary using Comprehension
bio = { key : list(value) for key in keys }


print("Before Change in Value:", bio)


value.clear()


print("After Change in Value:", bio)


Output.

Now, the concept should be clear. In case 1, changes made to the value list lead to changes in the value for the dictionary key items, while in the second case, changes made to the value list do not lead to any change in the generated dictionary.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *