python - pythonic方法来打破一个字典,哪个值是几个字典的列表
问题描述
描述
- 我需要打破一个字典,它的值是几个字典的列表,保留其他部分。
- 我要破解的键可能有不同的名称,但
cond
唯一且总是得到一个类型的值是list
.
例子
- 输入
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
- 它有效,但我认为它不是最好的 pythonic 解决方案。
问题:
- 任何更好的pythonic解决方案?
解决方案
类似于下面的内容(解决方案基于我认为代表一般情况的帖子的输入)
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'}]
推荐阅读
- visual-studio-code - 是否可以在 RKE 集群上使用 Cloud-Code(在 VSCode 内)?
- c# - 从 SQL Server 检索图像到 ASP.NET imagebutton
- kubernetes - 获取 Docker 容器的请求
- excel - 循环/分配 MaxValue、MinValue 和计算间隔
- parsing - UnicodeDecodeError 发生在 .p 文件中(pickle)
- python - 使用 defaultdict 和组合计数对给出“不可散列的类型:'list'”
- python - Kivy - 居中 BoxLayout
- python - 如何在验证码上使用 Selenium 打开浏览器窗口?
- kivy - 使用滚动视图重新创建 kivy 应用程序以用作屏幕管理器的屏幕
- javascript - 如何加载 UTC 数字日期并将其转换为 unix +new Date()?