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):
d[j].append(i)
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:
d[scope_item].append(relation)
An option would then will be replacing
d[scope_item].append(relation)
with
if d.has_key(scope_item):
d[scope_item].append(relation)
else:
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?