如何使用列表中的值将默认dict解析为独立的dicts

问题描述 投票:-1回答:1

试图解析defaultdict(列表)

输入:

defaultdict(class <'list'>,{'key1': ['v1', 'v2'], 'key2': [v3, v4], 'key3': ['v5', 'v6']})

期望的输出:

list_dic = [{key1: v1, key2: v3, key3: v5}, {key1: v2, key2: v4, key3: v6}] 

必须在列表中使用n个值。

从所需的输出开始,我打算使用mysql executemany将这些值插入到db中。如果有人对如何在mysql中的表中插入deafaultdict(列表)有任何更好的建议 - 我会很感激。

python-3.x dictionary data-structures mapping defaultdict
1个回答
0
投票

对我来说,答案在于嵌套在列表理解中的词典理解。请注意,这段代码依赖于输入特定是一个字典,所有列表的长度相同!

要测试它,请运行:

n = len(list(input.values())[0]
all_length_equal = all([len(v)==n for v in input.values()])

完成后,下面的代码会遍历每个值,获取i值,并将商店存入dictionnary,尝试使用0:

{k:v[0] for k,v in input.items()}

然后你需要添加一个列表理解

[ i for for i in range(len(list(input.values())[0])]

以上将返回一个数字范围。但是如果你将两者结合起来,它将在第一个值的长度范围内返回带有i的字典。

list_dic = [{
     k:v[i] for k,v in input.items() #This create the correct dictionnary with all the i-values in the input
} for i in range(len(list(input.values())[0])] # iterate through the length of the first list
© www.soinside.com 2019 - 2024. All rights reserved.