我有一个由混合字典和列表组成的数据结构。我试图解压缩这个以获得密钥的元组和每个密钥的所有子值。
我正在使用列表推导,但只是没有让它工作。我哪里错了?
我看到了许多关于解压缩列表列表的其他答案(例如1,2),但找不到单个键解包多个子值的示例。
代码:
dict_of_lists = {'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] }
print [(key,subdict[subkey],) for key in dict_of_lists.keys() for subdict in dict_of_lists[key] for subkey in subdict.keys()]
答案 0 :(得分:5)
当列表理解成为
时抛弃它们并每次都使用手册循环:
Class
def unpack(d):
for k, v in d.iteritems():
tmp = []
for subdict in v:
for _, val in subdict.iteritems():
tmp.append(val)
yield (k, tmp[0], tmp[1])
print list(unpack({'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] }))
<强>输出:强>
def unpack(d):
for k, v in d.items():
tmp = []
for subdict in v:
for _, val in subdict.items():
tmp.append(val)
yield (k, *tmp) # stared expression used to unpack iterables were
# not created yet in Python 2.x
print(list(unpack({'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] })))
答案 1 :(得分:1)
遍历dicts列表并仅获取值。然后与dict键结合使用。
>>> for k,L in dict_of_lists.iteritems():
... print tuple( [k]+[v for d in L for v in d.values()])
('A', 1, 2)
('B', 3, 4)
如果你需要一个班轮:
>>> map(tuple, ([k]+[v for d in L for v in d.values()] for k,L in dict_of_lists.iteritems()))
[('A', 1, 2), ('B', 3, 4)]