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
from collections import defaultdict
input = [( 'bhanu' , 'html' ),
( 'bhanu' , 'php' ),
( 'suma' , 'python' ),
( 'rasmi' , 'java' ),
( 'suma' , 'html/csscss' )]
data = defaultdict( list )
for key, value in input :
data[key].append(value)
print (data.items())
|
Output:
dict_items([(‘bhanu’, [‘html’, ‘php’]), (‘suma’, [‘python’, ‘html/csscss’]), (‘rasmi’, [‘java’])])
Example 2:
Python3
from collections import defaultdict
input = [( 'bhanu' , 10 ), ( 'uma' , 12 ), ( 'suma' , 11 )]
data = defaultdict( list )
for key, value in input :
data[key].append(value)
print (data.items())
|
Output:
dict_items([('bhanu', [10]), ('uma', [12]), ('suma', [11])])