How to create a dictionary whose elements are lists?

0 votes
I want to create a dictionary whose values are lists. What is the best way to achieve this? Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?
Aug 7 in Python by Neel
• 3,010 points
55 views

1 answer to this question.

0 votes

A simple way to do this is by using defaultdict.The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want. You can refer to the following code to know more.

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
...   for j in range(int(i), int(i) + 2):
...     d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]
answered Aug 7 by Arvind
• 2,960 points

Related Questions In Python

0 votes
1 answer

How to correctly return an a dictionary as an output in zappier code using python?

David here, from the Zapier Platform team. ...READ MORE

answered Dec 3, 2018 in Python by charlie_brown
• 7,720 points
111 views
0 votes
1 answer

How to create and read from a temporary file in Python?

Hi, there is a very simple solution ...READ MORE

answered Jan 29 in Python by Nymeria
• 3,520 points
67 views
0 votes
1 answer

How to create a GUID/UUID in Python

The uuid module, in Python 2.5 and ...READ MORE

answered Jan 29 in Python by SDeb
• 13,160 points
105 views
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 232 views
+4 votes
6 answers
0 votes
1 answer

How to access the elements of a dictionary using index ?

Suppose you have a dictionary num = ...READ MORE

answered Jul 4 in Python by Arvind
• 2,960 points
13 views
0 votes
1 answer

Is it possible to create a dictionary with multiple keys for a single value?

One thing that you can do here ...READ MORE

answered Jul 24 in Python by Arvind
• 2,960 points
24 views