python - 如何根据另一个字典值创建字典

标签 python

我有一个字典列表,类似这样

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/

相关文章:

python - 如果对象的 __hash__ 发生变化会发生什么?

python - 如何计算两列之间的模糊比?

Python 时间戳正则表达式

python - 在字符串中查找列表元素

python - jupyter nbconvert 不为 matplotlib.savefig 保存文件

python - 使用 ELEMNTREE 和 Beautifulsoup 解析 XML 时遇到内存问题

python - pandas groupby 对象到数据框

python - 如何运行 django-admin 检查命令?

python - Pandas 按月数之间的月数分组

python - 在函数中定义变量范围