0

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!

4

1 回答 1

2

您是否有理由需要以这种方式构建字典?你可以简单地定义

d = {'string': [('a', 'b'), ('c', 'd'), ('e', 'f')], 'string2': [('a', 'b'), ('z', 'x')]}

如果你想要一个新条目:

d['string3'] = [('a', 'b'), ('k', 'l')]

如果您希望将元组附加到您的列表之一:

d['string2'].append(('e', 'f'))

现在您的问题更清楚了,假设您事先知道某个列表中的键,只需构造一个带有循环的字典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'))

如果您只想先构建字典,还有一个字典理解:

d = {k: [] for k in keys}

感谢你的回答。但是,有没有办法使用 defaultdict 来做到这一点?

from collections import defaultdict

d = defaultdict(list)

for i in 'string1','string2':
   d[i].append(('a','b'))

或者您可以使用setdefault

 d = {}
 for i in 'string1','string2':
     d.setdefault(i, []).append(('a','b'))
于 2013-09-07T20:26:22.747 回答