Home > Software engineering >  How to extract from a dictionary based on a key value in python
How to extract from a dictionary based on a key value in python

Time:12-06

Lets say i have a dictionary like this:

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

What I want is to have another dictionary in which I have only elements which some key is equal to something (in my case i want to keep all elements where key4 = Book1) How can I have another dictionary that looks like this:

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

CodePudding user response:

First of all, there's no such thing as null in python, it's None. Second, this might work the way you want

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

CodePudding user response:

Simple one liner:

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

Assuming you call your initial dict data.

  • Related