Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

I need to make a dictionary whose values were lists. For instance: 


  1: ['1'],

  2: ['1','2'],

  3: ['2']


If I do:

d = dict()

a = ['1', '2']

for i in a:

    for j in range(int(i), int(i) + 2): 


I get a KeyError, in light of the fact that d[...] isn't a list. For this situation, I can add the accompanying code after the task of a to instate the dictionary. 

for x in range(1, 4):

    d[x] = list()

Is there a superior method to do this? Let's say I don't have a clue about the keys I will require until I am in the second for loop. For instance: 

class relation:

    scope_list = list()


d = dict()

for relation in relation_list:

    for scope_item in relation.scope_list:


An option would then will be replacing 



if d.has_key(scope_item):



    d[scope_item] = [relation,]

What is the most ideal approach to deal with this? In a perfect world, annexing would "simply work". Is there some approach to express that I need a dictionary of empty list, regardless of whether I don't have the foggiest idea about each key when I initially make the list?

1 Answer

0 votes
by (26.4k points)
edited by

You can try to use defaultdict:

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

Want to become a expert in Python? Join the python course fast!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
4 answers

Browse Categories