I want to create a dictionary whose values are lists. For example:
{1: ['1'], 2: ['1', '2'], 3: ['1', '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, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary.
for x in range(1, 4):
d[x] = list()
Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second for
loop. For example:
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 alternative would then 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 best way to handle this? Ideally, appending would "just work". 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?