Skip to content

Python dictionary same key multiple values | Example code

  • by

Just associate the list object to a key if you want the same key to have multiple values in the Python dictionary. A list object will have multiple elements.

d = {'a': [1,2],
    'b': [2,3],
    'c': [4,5]}

print(d)

Example dictionary same key multiple values in Python

Simple example code where multiple values in a list correspond to the key so that the list becomes the one value corresponding to the key:

Create a dictionary where multiple values are associated with a key

word_freq = {'A': [1, 3, 4, 8, 10],
             'B': [3, 10, 15, 7, 9],
             'C': [5, 3, 7, 8, 1],
             'D': [2, 3, 5, 6, 11],
             'E': [10, 3, 9, 8, 12]}

print(word_freq)

Output:

Python dictionary same key multiple values

Get multiple values of a key in the dictionary

word_freq = {'A': [1, 3, 4, 8, 10],
             'B': [3, 10, 15, 7, 9],
             'C': [5, 3, 7, 8, 1],
             'D': [2, 3, 5, 6, 11],
             'E': [10, 3, 9, 8, 12]}

value_list = word_freq['A']
print(value_list)

Output: [1, 3, 4, 8, 10]

Append multiple values to a key in a dictionary

my_dict = {"a": [1, 2], "b": [3, 4]}

print(my_dict)

my_dict["b"].append(5)

print(my_dict)

Output:

{‘a’: [1, 2], ‘b’: [3, 4]}
{‘a’: [1, 2], ‘b’: [3, 4, 5]}

Use the defaultdict Module to Add Multiple Values to a Key in a Dictionary

from collections import defaultdict
s = [('rome', 1), ('paris', 2), ('newyork', 3), ('paris', 4), ('delhi', 1)]
d = defaultdict(list)

for k, v in s:
    d[k].append(v)
sorted(d.items())

print(d)

Output:

defaultdict(<class 'list'>,
            {'rome': [1],
             'paris': [2, 4], 
             'newyork': [3],
             'delhi': [1]
            }) 

Use the setdefault() Method to Add Multiple Values to a Specific Key in a Dictionary

s = [('rome', 1), ('paris', 2), ('newyork', 3), ('paris', 4), ('delhi', 1)]
data_dict = {}

for x in s:
    data_dict.setdefault(x[0], []).append(x[1])
    
print(data_dict)

Output: {‘rome’: [1], ‘paris’: [2, 4], ‘newyork’: [3], ‘delhi’: [1]}

Do comment if you have any doubts or suggestions on this Python multiply program.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *