Open In App
Related Articles

Python – Add values to Dictionary of List

Improve Article
Improve
Save Article
Save
Like Article
Like

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 module
from collections import defaultdict
 
# declare a list with student data
input = [('bhanu', 'html'),
         ('bhanu', 'php'),
         ('suma', 'python'),
         ('rasmi', 'java'),
         ('suma', 'html/csscss')]
 
# declare a default dict
data = defaultdict(list)
 
# append to the dictionary
for key, value in input:
    data[key].append(value)
 
# display
print(data.items())


Output:

dict_items([(‘bhanu’, [‘html’, ‘php’]), (‘suma’, [‘python’, ‘html/csscss’]), (‘rasmi’, [‘java’])])

Example 2:

Python3




# import defaultdict module
from collections import defaultdict
 
# declare a list with student data with age
input = [('bhanu', 10), ('uma', 12), ('suma', 11)]
 
# declare a default dict
data = defaultdict(list)
 
# append to the dictionary
for key, value in input:
    data[key].append(value)
 
# display
print(data.items())


Output:

dict_items([('bhanu', [10]), ('uma', [12]), ('suma', [11])])

Last Updated : 01 Dec, 2021
Like Article
Save Article
Similar Reads
Related Tutorials