[英]removing values from a python dictionary
早上好。 我有一些嵌套字典,每個鍵有多個項目。 我只需要提取包含只有“ans”和“val”對的項目的對,如果項目包含“ans”、“type”、“value”等,那么我想刪除它。 我擁有的字典示例和預期的 output 如下所示。 歡迎任何建議,非常感謝
數據
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"},
],
}
預計 output
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'}]}
從字面上看,將您的 dicts 列表過濾為恰好具有兩個鍵的那些,並且具有您感興趣的兩個鍵值。
dict_i_want = dict()
for key, values in dict_i_have.items():
subdicts = [d for d in values if len(d) == 2 and 'ans' in d and 'val' in d]
dict_i_want[key] = subdicts
嘗試以下簡單的解決方案,
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"},
],
}
# Actual Solution starts here
for key1 in dict_i_have:
for val in dict_i_have[key1]:
if len(val) > 2 :
dict_i_have[key1].remove(val)
print(dict_i_have)
您可以通過字典理解來做到這一點:
dict_i_have = {
# elided for brevity
}
dict_i_want = {
key: [
{"ans": q["ans"], "val": q["val"]} for q in questions if "val" in q
]
for (key, questions) in dict_i_have.items()
}
print(dict_i_want)
或者,如果您想保留對原始字典的引用而不是將它們復制到新字典中,
dict_i_want = {
key: [q for q in questions if set(q) == {"ans", "val"}]
for (key, questions) in dict_i_have.items()
}
print(dict_i_want)
使用字典keys
function 可以得到字典中的鍵。
然后將其與{"ans", "val"}
進行比較以過濾掉不需要的字典。
for key in dict_i_have.keys():
dict_i_have[key] = [item for item in dict_i_have[key] if set(item.keys()) == {'ans', 'val'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.