如何将列表字典(字典!)和 return 解包为分组元组?

How to unpack a dictionary of list (of dictionaries!) and return as grouped tuples?

我有一个由混合字典和列表组成的数据结构。我正在尝试解压缩它以获得键的元组和每个键的所有子值。

我正在使用列表理解,但就是无法正常工作。我哪里错了?

我看到许多关于解包列表列表的其他答案(例如 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()]

当列表解析变为

  • unclear/hard阅读
  • 最重要的是,不起作用

放弃它们,每次都使用手册 for 循环:

Python 2.x

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}] }))

Python 3.x

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}] })))

输出:

[('A', 1, 2), ('B', 3, 4)]

遍历字典列表并只获取值。然后结合字典键。

>>> 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)]