gpt4 book ai didi

python - 将嵌套元组转换为嵌套字典

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:49 24 4
gpt4 key购买 nike

我有一个字典列表,其中有一些元组作为它们的值:

dic1 = {
'persuaded ': [[('teacher', '6'), ('group', '5'), ('man', '5'), ('girl', '5')]],
'removed ': [[('apple', '5'), ('makeup', '4'), ('trash', '4'), ('stain', '4')]]
}

我需要做的是将嵌套的元组转换为字典,以便之后可以使用键将其与其他类似列表进行比较。理想的结果应该是这样的:

dic2 = {
'persuaded ': [{'teacher': '6'}, {'group': '5'}, {'man': '5'}, {'girl': '5'}],
'removed ': [{'apple': '5'}, {'makeup': '4'}, {'trash': '4'}, {'stain': '4'}]
}

我试过:

dic2 = {}
for x, y in dic1_zipped:
d.setdefault(x, []).append(y)

和:

from collections import defaultdict
dic2= defaultdict( list )
for n,v in dic1_zipped:
fq[n].append(v)

但在字典中都不够深入。我真的很感激任何关于如何解决这个问题的建议!谢谢!

最佳答案

以下嵌套的字典和列表理解将为您完成:

dic2 = {key: [{k: v} for sublist in value for k, v in sublist] for key, value in dic1.items()}

演示:

>>> {key: [{k: v} for sublist in value for k, v in sublist] for key, value in dic1.items()}
{'removed ': [{'apple': '5'}, {'makeup': '4'}, {'trash': '4'}, {'stain': '4'}], 'persuaded ': [{'teacher': '6'}, {'group': '5'}, {'man': '5'}, {'girl': '5'}]}
>>> from pprint import pprint
>>> pprint(_)
{'persuaded ': [{'teacher': '6'}, {'group': '5'}, {'man': '5'}, {'girl': '5'}],
'removed ': [{'apple': '5'}, {'makeup': '4'}, {'trash': '4'}, {'stain': '4'}]}

我真的很惊讶你不想为每个值一个字典:

dic2 = {key: {k: v for sublist in value for k, v in sublist} for key, value in dic1.items()}

产生:

>>> {key: {k: v for sublist in value for k, v in sublist} for key, value in dic1.items()}
{'removed ': {'stain': '4', 'trash': '4', 'apple': '5', 'makeup': '4'}, 'persuaded ': {'group': '5', 'teacher': '6', 'man': '5', 'girl': '5'}}
>>> pprint(_)
{'persuaded ': {'girl': '5', 'group': '5', 'man': '5', 'teacher': '6'},
'removed ': {'apple': '5', 'makeup': '4', 'stain': '4', 'trash': '4'}}

关于python - 将嵌套元组转换为嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20150122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com