Python – Add values to Dictionary of List
In this article, we will discuss how to add values to the dictionary of lists.
We can add values to a dictionary by using a list, the input list would be the following structure:
[('key',value),...........,('key',value)]So the above list is an input, which we can use with for loop to add values to the dictionary of lists.
Syntax:
for key, value in input:
data[key].append(value)
where,
- key is the key in the input list
- value is the value in the input list
Example 1: Python program to create an input list of students subjects and add to the dictionary of list
Python3
# import defaultdict modulefrom collections import defaultdict# declare a list with student datainput = [('bhanu', 'html'), ('bhanu', 'php'), ('suma', 'python'), ('rasmi', 'java'), ('suma', 'html/csscss')]# declare a default dictdata = defaultdict(list)# append to the dictionaryfor key, value in input: data[key].append(value)# displayprint(data.items()) |
Output:
dict_items([(‘bhanu’, [‘html’, ‘php’]), (‘suma’, [‘python’, ‘html/csscss’]), (‘rasmi’, [‘java’])])
Example 2:
Python3
# import defaultdict modulefrom collections import defaultdict# declare a list with student data with ageinput = [('bhanu', 10), ('uma', 12), ('suma', 11)]# declare a default dictdata = defaultdict(list)# append to the dictionaryfor key, value in input: data[key].append(value)# displayprint(data.items()) |
Output:
dict_items([('bhanu', [10]), ('uma', [12]), ('suma', [11])])


