我有一个字典列表,类似这样
input = [
{"0_question": "how are you"},
{"0_answer": "good"},
{"4_question": "what time is it"},
{"4_answer": "morning"},
]
我想要这个:
expected_result = {
0: {"how are you": "good"},
4: {"what time is it" : "morning"},
}
这是我尝试过的:
x = {}
l= []
for i, d in enumerate(a):
for k, v in d.items():
l.append(v)
x[l[i]] = l[i+1]
最佳答案
将原始dict key
拆分为数字和类型部分:
a = [
{
"0_question": "how are you"
}, {
"0_answer": "good"
}, {
"4_question": "what time is it"
}, {
"4_answer": "morning"
}
]
dic = {}
for item in a:
value = list(item.values())[0]
num, itemType = list(item.keys())[0].split('_')
num = int(num)
if itemType == 'question':
dic[num] = {value: ''}
else:
key = list(dic[num].keys())[0]
dic[num][key] = value
print(dic)
输出:
{0: {'how are you': 'good'}, 4: {'what time is it': 'morning'}}
关于python - 如何根据另一个字典值创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73322109/