簡體   English   中英

如何根據 python 中的鍵值從字典中提取

[英]How to extract from a dictionary based on a key value in python

可以說我有一本這樣的字典:

{
    "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"
        }
    ]
}

首先,python中沒有null這樣的東西,它是None。 其次,這可能會以您想要的方式工作

newDict = {"test1": []}
for i in oldDict["test1"]:
    if i['key4'] == 'Book1':
        newdict["test1"].append(i)

簡單的一個班輪:

{"test1": [d for d in data["test1"] if d["key4"] == "Book1"]}

假設您調用初始 dict data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM