w3resource

Python: Map two lists into a dictionary

Python dictionary: Exercise-13 with Solution

Write a Python program to map two lists into a dictionary.

Sample Solution:

Python Code:

# Create a list 'keys' containing color names.
keys = ['red', 'green', 'blue']

# Create another list 'values' containing corresponding color codes in hexadecimal format.
values = ['#FF0000', '#008000', '#0000FF']

# Use the 'zip' function to pair each color name with its corresponding color code and create a list of tuples.
# Then, use the 'dict' constructor to convert this list of tuples into a dictionary 'color_dictionary'.
color_dictionary = dict(zip(keys, values))

# Print the resulting 'color_dictionary' containing color names as keys and their associated color codes as values.
print(color_dictionary)

Sample Output:

{'red': '#FF0000', 'green': '#008000', 'blue': '#0000FF'}

Python Code Editor:

Previous: Write a Python program to remove a key from a dictionary.
Next: Write a Python program to sort a dictionary by key.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-13.php