Python: Map two lists into a dictionary
13. Map Two Lists into a Dictionary
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'}
For more Practice: Solve these Related Problems:
- Write a Python program to convert two lists of equal length into a dictionary using the zip() function.
- Write a Python program to map two lists into a dictionary, handling duplicate keys by storing values in a list.
- Write a Python program to implement a function that takes two lists and returns a dictionary where keys come from the first list and values from the second.
- Write a Python program to use dictionary comprehension to create a dictionary from two lists.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics