假設我有一本這樣的字典:
{
"test1": [{
"key1": "123",
"key2": "456",
"key3": null,
"key4": "Book1"
}, {
"key1": "123",
"key2": "456",
"key3": null,
"key4": "Book2"
}, {
"key1": "12311",
"key2": "45678",
"key3": null,
"key4": "Book1"
}, {
"key1": "123",
"key2": "456",
"key3": null,
"key4": "Book4"
}, {
"key1": "12322",
"key2": "45690",
"key3": null,
"key4": "Book1"
}
]
}
我想要的是擁有另一本字典,其中我只有某些鍵等于某事物的元素(在我的情況下,我想保留 key4 = Book1 的所有元素)我怎樣才能擁有另一本看起來像這樣的字典:
{
"test1": [{
"key1": "123",
"key2": "456",
"key3": null,
"key4": "Book1"
}, {
"key1": "12311",
"key2": "45678",
"key3": null,
"key4": "Book1"
}, {
"key1": "12322",
"key2": "45690",
"key3": null,
"key4": "Book1"
}
]
}
uj5u.com熱心網友回復:
首先,python中沒有null這樣的東西,它是None。其次,這可能會以您想要的方式作業
newDict = {"test1": []}
for i in oldDict["test1"]:
if i['key4'] == 'Book1':
newdict["test1"].append(i)
uj5u.com熱心網友回復:
簡單的一個班輪:
{"test1": [d for d in data["test1"] if d["key4"] == "Book1"]}
假設您呼叫初始 dict data。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375710.html
上一篇:尋找函式語法來根據兩個不同的字典鍵/值對檢查資料框列?
下一篇:協助使用Python中的字典?
