Python Dictionary fromkeys() Usage With Example

Python dictionary fromkeys() method is used to create a dictionary from the given keys (keys can be string, list, tuple, set e.t.c). It is sometimes necessary to create a dictionary from the given keys and this keys value might be provided in the form of iterables. Python provides us with different methods for the dictionary iterable, these methods would be useful for handling dictionary-related issues.

In this article, I will explain how to create a dictionary from keys by using a Python dictionary fromkeys() method

Quick examples of Python dictionary fromkeys()

Following are the quick examples of Python Dictionary fromkeys().


# Example 1: Create a dictionary using fromkeys()
courses={"Spark","PySpark","Hadoop","Python"}
value1="language"
dictionary=dict.fromkeys(courses, value1) 

# Example 2: Create dictionary with no value parameter
dictionary=dict.fromkeys(courses) 

# Example 3: Using string as a key parameter
course = 'python'
value1 = 'character'
dictionary= dict.fromkeys(course, value1)

# Example 4: Create a dictionary using fromkeys()
courses=["Spark","PySpark","Hadoop","Python"]
value1="language"
dictionary=dict.fromkeys(courses, value1) 

# Example 5: Create a dictionary pass the list as a value parameter in fromkeys()
courses=["Spark","PySpark","Hadoop","Python"]
dictionary=dict.fromkeys(courses, ['language']) 
value1.append('technology')

# Example 6: Create a dictionary using dictionary comprehension 
courses=["Spark","PySpark","Hadoop","Python"]
value1=['language']
dictionary={key: list(value1) for key in courses}
print("dictionary:", dictionary)
value1.append('technology') 
print("new dictionary:", dictionary) 

1. Syntax of the fromkeys()

Following is the syntax of the fromkeys().


# Syntax of fromkeys()
dict.fromkeys(sequence,value)

1.2 fromkeys() method Parameters

fromkeys() method allows two parameters:

  • Sequence: A sequence is an iterable object which will use as key for the new dictionary.
  • Value: Is a value of each key, it defaults to None and optional.

1.3 Return value of Python Dictionary fromkeys()

The fromkeys() method returns a new dictionary with the given iterable object as the keys of the dictionary and value with a specific value to the method.

2. Usage of Python Dictionary fromkeys()

Python dictionary fromkeys() creates a new dictionary from the given iterable objects such as string, list, tuple, and set as keys and with a specified value. If no value is specified to value param, the values of keys are set to None by default.


# Create a dictionary using fromkeys()
courses ={"Spark","PySpark","Hadoop","Python"}
dictionary=dict.fromkeys(courses,'language') 
print(dictionary)

# Output:
{'Spark': 'language', 'PySpark': 'language', 'Hadoop': 'language', 'Python': 'language'}

This creates a dictionary using the fromKeys() method where the values from courses list used as keys and language as value for all elements in dict.

2.1 Default Behaviour sets None Value

In case you do not want to set any specific value to the dictionary keys, do not specify the value param, this by default set the value None for all dictionary elements.


# Create dictionary with no value parameter
courses={"Spark","PySpark","Hadoop","Python"}
dictionary=dict.fromkeys(courses) 
print(dictionary)

# Output:
{'Spark': None, 'PySpark': None, 'Hadoop': None, 'Python': None}

3. Use string as a key Parameter of fromkeys().

Create a dictionary using a string as a key parameter by using fromkeys() method. By using String, each character in the String will be converted to a key.


# Create a dictionary using  a string as a key parameter
course = 'python'
value1 = 'character'
dictionary= dict.fromkeys(course, value1)
print(dictionary)

# Output:
{'p': 'character', 'y': 'character', 't': 'character', 'h': 'character', 'o': 'character', 'n': 'character'}

4. Use list to value Parameter

Let’s see an example of assigning list to a value param. Python dictionary fromkeys() can also pass list( mutable object) as the default value. However, in this situation, an in-depth copy of the dictionary will create, which means that if we append a value to the original list, which will updates in all key values. This is because each element has a reference to the same object(points to the same object in the memory).


# Create a dictionary pass the list as a value parameter in fromkeys()
courses=["Spark","PySpark","Hadoop","Python"]
value1=['language']
dictionary=dict.fromkeys(courses, value1) 
print("dictionary:", dictionary)
value1.append('technology')
print("new dictionary:", dictionary)

Yields below output


dictionary: {'Spark': ['language'], 'PySpark': ['language'], 'Hadoop': ['language'], 'Python': ['language']}
new dictionary: {'Spark': ['language', 'technology'], 'PySpark': ['language', 'technology'], 'Hadoop': ['language', 'technology'], 'Python': ['language', 'technology']}

To overcome above deep copy problem, we can use dictionary comprehension.


# Create a dictionary using dictionary comprehension 
courses=["Spark","PySpark","Hadoop","Python"]
value1=['language']
dictionary={key: list(value1) for key in courses}
print("dictionary:", dictionary)
value1.append('technology') 
print("new dictionary:", dictionary) 

Yields below output


dictionary: {'Spark': ['language'], 'PySpark': ['language'], 'Hadoop': ['language'], 'Python': ['language']}
new dictionary: {'Spark': ['language'], 'PySpark': ['language'], 'Hadoop': ['language'], 'Python': ['language']}

Here, a new list of values is formed and assigned to each key in courses. In summary, value1 is not assigned to the element, but a new list is created from it and assigned to each element in the dictionary.

7. Conclusion

In this article, I have explained how to create a dictionary from list/set of keys by using using the fromkeys() method. Also, I have explained While creating a dictionary using fromkeys() how can we use its keys, and values by the users.

Happy Learning !!

References

Related Articles

Leave a Reply

You are currently viewing Python Dictionary fromkeys() Usage With Example