mzage mzage - 1 month ago 4x
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 :


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

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


data = json.load(open('json.json'))
R = 'C' #user input

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


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:
        break # if there can be more that one match then remove