Jay Tee
Jay Tee

Reputation: 11

How to loop through a list of dictionary and select specific key value python

So I have the following list of dictionary:

"Items": [{
        "Instance": 1,
        "SubInstance": 1,
        "Path": "To Sleep",
    },
    {
        "Instance": 1,
        "SubInstance": 2,
        "Path": "To Eat",
    },
    {
        "Instance": 3,
        "SubInstance": 1,
        "Path": "To Play"
    },
    {
        "Instance": 2,
        "SubInstance": 1,
        "Path": "To Work"
    }]

And I am trying to loop through the list and check for if Instance = 3 and SubInstance = 1 then select just the key value "To Play" and assign it to a variable path_result. User input variables to use are var_inst for Instance and var_subInst for Subinstance. Thanks.

Upvotes: 0

Views: 3969

Answers (1)

Felix Martinez
Felix Martinez

Reputation: 359

for item in l:
    if item['Instance'] == 3 and item['SubInstance'] == 1:
        path_result = item['Path']

l is a list of dictionaries

Upvotes: 2

Related Questions