首页 > 解决方案 > pythonic方法来打破一个字典,哪个值是几个字典的列表

问题描述

描述

例子

cond = {"type":"image","questionType":["3","4","5"]}

cond = {"type":"example","fieldToBreak":["1","2","3"],"fieldInt":1,"fieldFloat":0.1}
[
    {'type': 'image', 'questionType': '3'}, 
    {'type': 'image', 'questionType': '4'}, 
    {'type': 'image', 'questionType': '5'}
]

[
    {'type': 'example', 'fieldToBreak': '1', 'fieldInt': 1, 'fieldFloat': 0.1},
    {'type': 'example', 'fieldToBreak': '2', 'fieldInt': 1, 'fieldFloat': 0.1},
    {'type': 'example', 'fieldToBreak': '3', 'fieldInt': 1, 'fieldFloat': 0.1}
]

我试过的

cond_queue = []
for k,v in cond.items():
    if isinstance(v,list):
        for ele in v:
            cond_copy = cond.copy()
            cond_copy[k] = ele
            cond_queue.append(cond_copy)
        break

问题:

标签: pythondictionary

解决方案


类似于下面的内容(解决方案基于我认为代表一般情况的帖子的输入)

cond = {"type": "image", "questionType": ["3", "4", "5"]}
data = [{"type": "image", "questionType": e} for e in cond['questionType']]
print(data)

输出

[{'type': 'image', 'questionType': '3'}, {'type': 'image', 'questionType': '4'}, {'type': 'image', 'questionType': '5'}]

推荐阅读