mzage
mzage

Reputation: 378

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?

Upvotes: 1

Views: 27

Answers (2)

mcamacho
mcamacho

Reputation: 68

As Padraic Cunningham pointed out, you need to loop through your results. Your solution would look like this:

data = json.load(open('json.json'))
R = 'C' #user input
print([x for x in data['x'] if x.keys()[0] == R][0][R])

[x for x in data['x'] if x.keys()[0] == R] gives you all the dict with key R in a list. Assuming that you don't have repeated keys, pick the first element and access to its value.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

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

Upvotes: 3

Related Questions