0

I have a JSON file which I have converted into a dictionary using the code below:

Newdict=r.json()

r has the same data which newdict has.

Newdict= {'name':'jas','surname':'kumar','age':19,'country':'IN'}
{'name':'arch','surname':'sahu','age':29,'country':'Sl'}
{'name':'salman','surname':'khan','age':20,'country':'pk'}
{'name':'raju','surname':'reddy','age':32,'country':'usa'}

I want search for something like age = 20 then print salman.

martineau
  • 119,623
  • 25
  • 170
  • 301
Amit
  • 11
  • 1

3 Answers3

1

There are several dicts in the example, so you probably have some kind of list? Then you can do something like:

[d['name'] for d in dictList if d['age'] == 20]

Upd. As Ann Zen pointed out in the comments, this code would return you a list with a single value (or several values, if multiple dicts have age=20). If you're sure that there's only one value, that fits your filter, you can add [0] in the end, to get first result from that list.

Rayan Ral
  • 1,862
  • 2
  • 17
  • 17
  • 1
    This will return the name in a list. Add a subscription of `[0]` to only retrieve the name in a string. – Red Jun 19 '20 at 15:18
0

You can do

Newdict= [{'name':'jas','surname':'kumar','age':'19','country':'IN'},
{'name':'arch','surname':'sahu','age':'29','country':'Sl'},
{'name':'salman','surname':'khan','age':'20','country':'pk'},
{'name':'raju','surname':'reddy','age':'32','country':'usa'}]

for i in Newdict:
    if int(i['age']) == 20:
        print(i['name'])

OR

for i in Newdict:
    if i['age'] == '20':
        print(i['name'])

OR in one line

print([i['name'] for i in Newdict if int(i['age']) == 20][0])

Output

salman
Leo Arad
  • 4,452
  • 2
  • 6
  • 17
0

You can use dictionary keys to retrieve their corresponding values:

Newdict = [{'name':'jas','surname':'kumar','age':'19','country':'IN'},
           {'name':'arch','surname':'sahu','age':'29','country':'Sl'},
           {'name':'salman','surname':'khan','age':'20','country':'pk'},
           {'name':'raju','surname':'reddy','age':'32','country':'usa'}]

for d in Newdict:
    if int(d['age']) == 20:
        print(d['name'])

Output:

salman
Red
  • 26,798
  • 7
  • 36
  • 58