mzage mzage - 3 months ago 9
JSON Question

Find dict that has user inputted key from a list of dicts

python 3.5

hi i have this simple json.json file :

json

{"x": [
{"A": "B"},
{"C": "D"},
{"E": "F"}
]}


and i have this code to find the letter after A or C or E

python

data = json.load(open('json.json'))
R = 'C' #user input
print(data['x'][1][R])


How can I find which dict with has the key without knowing and hard coding the index of the dict?

Answer

So you want to find the value by searching without hard coding the index, what you need is a loop that checks each dict for the key:

data = json.load(open('json.json'))
R = 'C' #user input
for d in  data['x']:
    if R in d:
        print(d[R])
        break # if there can be more that one match then remove
Comments