早上好。我有一些嵌套字典,每个键有多个项。我只需要提取包含仅具有“ans”和“val”对的项的对,如果该项包含“ans”、“type”、“value”等,则我要将其删除。下面是我拥有的字典示例和预期输出。 欢迎任何建议,非常感谢
数据
dict_i_have = {
"x19": [
{
"ans": "Enter number",
"type": "number",
"value": "input_val",
"validators": [
{"dype": "int", "invalid": "Enter number between 0 and 100", "min": 0, "max": 100},
{"vtype": "no", "message": "Please enter a value"},
],
},
{"ans": "One year or less", "val": "-10"},
{"ans": "Do not know", "val": "1"},
{"ans": "Other", "val": "3"},
],
"x20": [
{
"ans": "Enter number",
"type": "number",
"value": "input_val",
"validators": [
{"dype": "int", "invalid": "Enter number between 0 and 50", "min": 0, "max": 50},
{"vtype": "no", "message": "Please enter a value"},
],
},
{"ans": "Six months or less", "val": "10"},
],
}
预期产出
dict_i_want = {'x19': [{'ans': 'One year or less', 'val': '-10'},
{'ans': 'Do not know', 'val': '1'},
{'ans': 'Other', 'val': '3'}],
'x20': [{'ans': 'Six months or less', 'val': '10'}]}
您可以通过字典理解来实现这一点:
或者如果你想保留对原始记录的引用,而不是复制到新记录中
从字面上说,将你的dict列表过滤到那些正好有两个键的dict列表,其中包含你感兴趣的两个键值
请尝试以下简单的解决方案
相关问题 更多 >
编程相关推荐