Answers for "multiple values in a dictionary python"

2

how to have multiple values to a key in dict in python

from collections import defaultdict
 data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
 d = defaultdict(list)
print (d) # output --> defaultdict(<type 'list'>, {})
 for year, month in data:
     d[year].append(month) 
print (d) # output --> defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})
Posted by: Guest on September-23-2020
0

dictionary multiple values per key

key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Posted by: Guest on June-14-2020

Code answers related to "multiple values in a dictionary python"

Python Answers by Framework

Browse Popular Code Answers by Language