Reputation: 127
Is it possible to create a dictionary like this in Python?
{'string':[(a,b),(c,d),(e,f)], 'string2':[(a,b),(z,x)...]}
The first error was solved, thanks! But, i'm doing tuples in a for loop, so it changes all the time. When i try to do:
d[key].append(c)
As c being a tuple.
I am getting another error now:
AttributeError: 'tuple' object has no attribute 'append'
Thanks for all the answers, i managed to get it working properly!
Upvotes: 0
Views: 1997
Reputation: 2553
Is there a reason you need to construct the dictionary in that fashion? You could simply define
d = {'string': [('a', 'b'), ('c', 'd'), ('e', 'f')], 'string2': [('a', 'b'), ('z', 'x')]}
And if you wanted a new entry:
d['string3'] = [('a', 'b'), ('k', 'l')]
And if you wish to append tuples to one of your lists:
d['string2'].append(('e', 'f'))
Now that your question is clearer, to simply construct a dictionary with a loop, assuming you know the keys beforehand in some list keys
:
d = {}
for k in keys:
d[k] = []
# Now you can append your tuples if you know them. For instance:
# d[k].append(('a', 'b'))
There is also a dictionary comprehension if you simply want to build the dictionary first:
d = {k: [] for k in keys}
Thanks for the answer. But, is there any way to do this using defaultdict?
from collections import defaultdict
d = defaultdict(list)
for i in 'string1','string2':
d[i].append(('a','b'))
Or you can use setdefault
:
d = {}
for i in 'string1','string2':
d.setdefault(i, []).append(('a','b'))
Upvotes: 2