如何解压缩列表(字典!)并作为分组元组返回?
作者:互联网
我有一个由混合字典和列表组成的数据结构.我试图解压缩这个以获得键的元组和每个键的所有子值.
我正在使用列表推导,但只是没有让它工作.我哪里错了?
我看到了许多关于解压缩列表列表的其他答案(例如1,2),但是找不到单个密钥针对多个子值解包的示例.
>期望的输出 – > [( ‘A’,1,2),( ‘B’,3,4)]
>实际输出 – > [(‘A’,1),(‘A’,2),(‘B’,3),(‘B’,4)]
码:
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()]
最佳答案:
当列表理解成为
>长
>不清楚/难以阅读
>最重要的是,不要工作
抛弃它们并每次都使用手册循环:
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)]
标签:python,dictionary,iterable-unpacking 来源: https://codeday.me/bug/20190516/1114687.html