In this Python guide, we’ll explain the concept of Python dictionary fromkeys method. We’ll first try to understand role of this method. After that, we’ll practically understand its usage with the help of multiple Python code examples.
Introduction: Python Dictionary Fromkeys Method
Its used to create a dictionary by using the provided keys and values sequence.
Let’s first walk through syntax of fromkeys() method. After that, we’ll jump into multiple Python code examples to properly understand usage of this method.
Syntax of fromkeys()
dict.fromkeys(keys,values)
- Python dictionary fromkeys method takes two arguments. First argument specifies the keys which can be an iterable like list, string, set etc. Second argument specifies the values in dictionary which can be of any type or an iterable like list, string, set etc.
- The fromkeys() method returns a new Python dictionary which contains keys and values of the given sequence. Not providing it a value will result in None assigned to all the keys.
Implementing Python Dictionary Fromkeys Method (Multiple Easy Examples)
Below examples will guide us through the proper usage of fromkeys method.
Example 1: fromkeys() with Keys and Values
keys = ['a','i','c','b'] values = 'Python' res = dict.fromkeys(keys,values) print(res)
Output
a': 'Python', 'i': 'Python', 'c': 'Python', 'b': 'Python'}
- In this example, we’ve created a Python list that will be used as keys and for the values, we’ve created a string. We can specify iterables to be used as values like list, set etc.
- Then we’ve called the fromkeys method of dictionary and have passed keys and values to them.
- We also have stored the result inside a variable.
- Finally, we’ve printed the variable and it shows a new dictionary in which the same value has been assigned to all the keys.
Example 2: fromkeys() with no Values
a=['a','b','c'] res=dict.fromkeys(a) print(res)
Output
{'a': None, 'b': None, 'c': None}
We can see that passing only keys to fromkeys() method will result in None assigned to all the keys in the newly created dictionary.
Example 3: fromkeys() method with Mutable Object
a = [1,2,3] b = [7,8,'abc'] res = dict.fromkeys(a,b) print(res)
Output
{ 1: [7, 8, 'abc'], 2: [7, 8, 'abc'], 3: [7, 8, 'abc']}
We’ve passed a list as value to fromkeys() method and we can see that this list has been assigned to all the keys. Let’s now update the list and see what changes it’ll make to the existing dictionary.
b.append('Zeeshan') print(res)
Output
{1: [7, 8, 'abc', 'Zeeshan'], 2: [7, 8, 'abc', 'Zeeshan'], 3: [7, 8, 'abc', 'Zeeshan']}
We’ve added a new item to the list(this list has been used as value in the dictionary). Then we’ve printed our dictionary and we can see that the values are also updated in the dictionary. Reason is that each element is pointing to the same address in memory.
We can solve it using dictionary comprehension. See below section.
Example 4: Dictionary Comprehension for Mutable Objects
By using this, we can stop our dictionary from being updated when the mutable object gets updated. See below code:
a = ['key1','key2','key3'] b = [2,3] res = {key:list(b) for key in a} print(res) b.append('Zeeshan') print(res)
Output
{'key1': [2, 3], 'key2': [2, 3], 'key3': [2, 3]} {'key1': [2, 3], 'key2': [2, 3], 'key3': [2, 3]}
In this code, we can see that the values of dictionary is not updated even if we update the list which has been used as value in the dictionary.
Reason is that we’ve not assigned values to the keys of dictionary. Instead, for each key in the keys(a), a new list of values(b) has been created. The new list has been assigned each key in the dictionary.
Example 5: Return Value of Python Dictionary Fromkeys Method
key = ['xx','yy','zz'] val = 'Python programming' returnValue = dict.fromkeys(key,val) print(returnValue)
Output
{'xx': 'Python programming', 'yy': 'Python programming', 'zz': 'Python programming'}
- We’ve first created a list of keys and a string value.
- Then we’ve applied fromkeys method on them and have stored the returned value inside a variable.
- Finally, we’ve printed the variable and we can see that this method returns a new dictionary in which the same value is assigned to all the keys.
Example 6: fromkeys() applied on Lists of Keys and Values using Python For Loop
keysList=[[1,2,3],('a','b','c'),{'a':234,'b':54}] valuesList=['Python',[9,8],{'name':'Zee'}] newList=[] for var1,var2 in zip(keysList,valuesList): newList.append(dict.fromkeys(var1,var2)) print(newList)
Output
[{1:'Python',2:'Python',3: 'Python'},{'a':[9, 8],'b':[9, 8],'c':[9, 8]},{'a':{'name': 'Zee'},'b':{'name': 'Zee'}}]
- In this program, we’ve created two Python lists. First list will be used as keys and second list as values.
- We also have created an empty list that’ll be used to store the newly created dictionaries.
- Then we’ve used Python for loop which will take items from both these lists while iterating over them. Click here to learn more about iterating over multiple Python lists simultaneously.
- In for loop’s body, we’ve applied fromkeys method which will take items of first list as keys and second list as values. Then it’ll add the result(newly created dictionaries) to the new list using its append method.
- Finally, we’ve displayed the new list in order to see the result. We can see that the desired output has been achieved.
So this is how we can easily make use of Python dictionary fromkeys method. Don’t hesitate to share it with other Python developers if this article has increased your knowledge.
Also, feel free to ask if you still have questions related to Python dictionary fromkeys method. We’ll be super happy to answer them all.
Conclusion
To conclude, hope you now have a detailed practical understanding of how to use Python dictionary fromkeys method. Do feel free to share your amazing feedback with us in the comment section.
Other worth reading posts on Python programming are also present on this site. Feel free to pay a visit to them as well. Thank you for reading this article.