Created
April 25, 2020 15:09
-
-
Save behnood-eghbali/b6eaa4e07c4033f858b96451f0ccdb42 to your computer and use it in GitHub Desktop.
Mapping Keys to Multiple Values in a Dictionary (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Mapping Keys to Multiple Values in a Dictionary with defaultdict (multidict) | |
# A dictionary is a mapping where each key is mapped to a single value. If you want to | |
# map keys to multiple values, you need to store the multiple values in another container | |
# such as a list or set. | |
from collections import defaultdict | |
first_dict = {'a': 1, 'b': 2, 'c': 3} | |
second_dict = defaultdict(list) | |
for key in first_dict: | |
second_dict[key] = list(first_dict.values()) | |
print(second_dict) | |
# defaultdict(<type 'list'>, {'a': [1, 3, 2]}) | |
# defaultdict(<type 'list'>, {'a': [1, 3, 2], 'c': [1, 3, 2]}) | |
# defaultdict(<type 'list'>, {'a': [1, 3, 2], 'c': [1, 3, 2], 'b': [1, 3, 2]}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Mapping Keys to Multiple Values in a Dictionary (multidict) | |
# A dictionary is a mapping where each key is mapped to a single value. If you want to | |
# map keys to multiple values, you need to store the multiple values in another container | |
# such as a list or set. | |
first_dict = {'a': 1, 'b': 2, 'c': 3} | |
second_dict = {} | |
for key in first_dict: | |
second_dict[key] = list(first_dict.values()) | |
print(second_dict) | |
# {'a': [1, 3, 2]} | |
# {'a': [1, 3, 2], 'c': [1, 3, 2]} | |
# {'a': [1, 3, 2], 'c': [1, 3, 2], 'b': [1, 3, 2]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment