How to make a dictionary (dict) from separate lists of keys and values?
|Often, we need to create a dictionary from separate lists of keys and values. in this Python example we will discuss some o the ways to create a dictionary from separate lists in Python.
Some of the topics which will be helpful for understanding the program implementation better are:
1. Using zip() Function
One of the simplest ways to create a dictionary from separate lists is to use the zip()
function. The zip()
function returns an iterator that aggregates elements from each of the input iterables.
Now let’s implement a program to create a dictionary from 2 separate lists.
keys = ['One', 'Two', 'Three'] values = [1, 2, 3] my_dict = dict(zip(keys, values)) print(my_dict)
Output {'One': 1, 'Two': 2, 'Three': 3}
2. Using a Dictionary Comprehension
We can use a dictionary comprehension to iterate over the keys
and values
lists simultaneously and create a dictionary.
Now lets implement the example again
keys = ['One', 'Two', 'Three'] values = [1, 2, 3] my_dict = {keys[i]: values[i] for i in range(len(keys))} print(my_dict)
Output {'One': 1, 'Two': 2, 'Three': 3}
There are other ways like using a for
loop to add elements to the empty dictionary but honestly, these are the better ways than implementing using a for
loop. So we will skip that example for now, but I would still recommend you to write the example using for
loop only.
3. Conclusion
In this Python example, we discussed multiple ways to create a dictionary from separate lists of keys and values.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?