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, 2019 in Python by Neel
• 3,010 points
139 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, 2019 by Arvind
• 2,980 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,760 points
204 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, 2019 in Python by Nymeria
• 3,540 points
182 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, 2019 in Python by SDeb
• 13,230 points
204 views
0 votes
1 answer

How to create Pandas series from dictionary?

Here's a sample script: import pandas as pd import ...READ MORE

answered Apr 1, 2019 in Python by Prateek
82 views
+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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 783 views
0 votes
0 answers
+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, 2019 in Python by Arvind
• 2,980 points
33 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, 2019 in Python by Arvind
• 2,980 points
51 views