我有字典列表,如下所示
A = [[{'a': '1', 'b': '2'}],[{...}],[{...}],[],[],[{'x': '25', 'z':'26'}]]
列表“A”中的 7 个字典列表(7 天的数据) python using for loop in def function
A 中的一些字典列表有数据,一些没有
我想像这样展平/展开到不同的列表 B
B = [{'a': '1', 'b': '2', ..., 'x': '25', 'z':'26'}]
作为字典列表。
我已经尝试过(带有相应的导入):
B = (list(itertools.chain(*A)))
B = [item for sublist in A for item in sublist]
B = [dict(chain(*map(dict.items, d.values()))) for d in A]
因此,以上 3 种展平/展开方法给了我一个空列表 []。 我想这样做是因为只有一个列表适合我在 html 中的 ajax 附加格式 这也将应用于月、季度、半年和年的数据集。(我还需要使用 for 循环将列表中的 365 个字典列表展平以创建此列表)
我上面的方法有错吗?
展平/展开是否必须遵循列表结构的每个无组织列表?
通过从 python using for loop in def function 更改 for 循环来创建像列表 A 那样的无组织列表会更好吗?
编辑:我在问题中分离了未展平列表(A)和展平列表(B)。
答案 0 :(得分:0)
您可以使用 itertools.chain()
和 dict 理解:
A = [[{1:1, 2:2}], [], [{3:3}], [{8:8}], [], [], [{9:9}]]
b = itertools.chain(*A)
{k:v for x in b for k,v in x.items()}
预期结果:
{1: 1, 2: 2, 3: 3, 8: 8, 9: 9}
有关 itertools 的更多信息:https://www.geeksforgeeks.org/python-itertools/
关于字典理解的更多信息:https://www.programiz.com/python-programming/dictionary-comprehension