Build a dictionary from a list of keys and values in Python
This post will discuss how to build a dictionary from a list of keys and values in Python.
For example, keys = ['A', 'B', 'C']
and values = [1, 2, 3]
should result in the dictionary {'A': 1, 'B': 2, 'C': 3}
.
1. Using zip()
with dict()
function
The simplest and most elegant way to build a dictionary from a list of keys and values is to use the zip()
function with a dictionary constructor.
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': keys = ['A', 'B', 'C'] values = [1, 2, 3] dictionary = dict(zip(keys, values)) print(dictionary) # {'A': 1, 'B': 2, 'C': 3} |
2. Using Dictionary Comprehension
Another approach is to use the zip()
with dictionary comprehension. This is often useful when you need value-key pairs instead of key-value pairs or apply some mapping function to each key or value. This can be implemented as:
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': keys = ['A', 'B', 'C'] values = [1, 2, 3] dictionary = {k: v for k, v in zip(keys, values)} print(dictionary) # {'A': 1, 'B': 2, 'C': 3} |
Here’s what the code would look like without zip()
:
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': keys = ['A', 'B', 'C'] values = [1, 2, 3] dictionary = {keys[i]: values[i] for i in range(len(keys))} print(dictionary) # {'A': 1, 'B': 2, 'C': 3} |
If you need to create a new dictionary with keys from iterable with the same value, you can do the following.
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': keys = ['A', 'B', 'C'] value = 1 dictionary = {key: value for key in keys} print(dictionary) # {'A': 1, 'B': 1, 'C': 1} |
Alternatively, you can use the fromkeys()
class function:
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': keys = ['A', 'B', 'C'] value = 1 dictionary = dict.fromkeys(keys, value) print(dictionary) # {'A': 1, 'B': 1, 'C': 1} |
That’s all about building a dictionary from a list of keys and values in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)