AmirTheDev
AmirTheDev

Reputation: 25

How to print the key which comes before the matching key in python dictionaries

I have the following json file

 {              
    "joseph":[
        {
            "id": "5983",
            "color": "green",
            "material": [ "wood" ],
        },
        {
            "id": "6983",
            "color": "red",
            "material": [ "Aluminum" ],
        },
        {
            "id": "5723",
            "color": "green",
            "material": [ "Iron" ],
        }
    ]
}

which I have converted to a python dictionary using the following code

import json
def p():
    # Opening JSON file
    with open('filed.json') as json_file:
        data = json.load(json_file)
      
        # for reading nested data [0] represents
        # the index value of the list
        
        # for printing the key-value pair of
        # nested dictionary for looop can be used
        print("\nPrinting nested dicitonary as a key-value pair\n")
        for i in data['joseph']:
            print("Name:", i["material"])

Now what I want to do is to print the value of the key "id" which is behind the key "material" that has the value wood, how do I do this?

Upvotes: 0

Views: 58

Answers (1)

Barmar
Barmar

Reputation: 781096

Use the in operator to test if a value is in a list. Then print the other key of the same dictionary.

for i in data['joseph']:
    if 'wood' in i['material']:
        print("Name:", i['id'])

Upvotes: 1

Related Questions