Monday, November 18, 2024
Google search engine
HomeLanguagesPython – Add values to Dictionary of List

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 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])])

RELATED ARTICLES

Most Popular

Recent Comments