简体   繁体   中英

How to print set from JSON array objects using Python

Iam working python json array objects.I am trying to print first set based on condition 0<=a<=21 I have to print 'number' item.Please help me.Thank you.

dic1 = [{'a':4,'b':5,'number':80},{'a':10, 'b':21,'number':200}]
for i in dic1:
  if 0<=i['a']<=21:
     print(i['number'])
  elif 17<=i['b']<=34:
     print(i['number'])

Output I got 80 80
What Actually I want.
if First condition is true output should be 80
if second condition true output should be 200

When I run your script it works. If you have a large number of dictionaries then this is not a good idea. But in this case, I would use the range function as it is more convenient. See the upper limit, if you want to include 21 you have to set it to 22 in python.

updates

based on your comment if you want the loop to be terminated after the first condition is reached, use the break statement

for dictionary in dic1:
    if dictionary['a'] in range(0, 21):
        print(dictionary['number'])
        break
    elif dictionary['b'] in range(17, 34):
        print(dictionary['number'])

By adding a break statement, loop breaks and only one of the if conditions is executed. That's how you won't get both the outputs.

dic1 = [{'a':4,'b':5,'number':80},{'a':10, 'b':21,'number':200}]
for i in dic1:
  if 0<=i['a']<=21:
     print(i['number'])
     break
  elif 17<=i['b']<=34:
     print(i['number'])
     break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM