How to handle dictionary keys that do not exist in a loop?

J Reigh :

I tried to parse json and use for loop in Python. obj is json and as you know it is like dictionary in list in dictionary in dictionary...and so on.

So I parse json and make it as a for loop like this:

all = obj['products']
for a in obj:
      recommendSellerScore.append(a['recommendSellerScore'])

However, the problem is 'recommendSellerScore' which is key does not exist in some lists.

What I want as a result is to print 'None' where recommendSellerScore does not exist, and print values where recommendSellerScore does exist.

for a in all:
    if a['recommendSellerScore'] in all:
        recommendSellerScore.append(a['recommendSellerScore'])
    else:
        continue
        print('None')

I ran this code above, but got an Error because 'recommendSellerScore' does not exist.

for a in all:
    if ['recommendSellerScore'] in all:
        recommendSellerScore.append(a['recommendSellerScore'])
    else:
        continue
        print('None')

This one worked, however, since 'recommendSellerScore' exists in list in dictionary, it was not iterable. (I guess)

Please fix my code, and any comments or advice will be appreciated!

Ayush Garg :

Here is fixed version of your code (I took out the continue statement and the [] around the string):

for a in all:
    if "recommendSellerScore" in a:
        recommendSellerScore.append(a["recommendSellerScore"])
    else:
        print("None")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170184&siteId=1