Python: Extracting multiple values from dict

x = json.loads(y)
z1 = (x[0][0])
z2 = (x[0][1])
z3 = (x[0][2])
z4 = (x[0][3])

etc...

How do we check if [4],[5],[6] exists in dict, then print/assign the result if it does?

Upvotes: 1

Views: 58

Answers (2)

IoaTzimas
IoaTzimas

Reputation: 10624

As @Antonio Margaretti indicated, you shall use x.get('key'). Your full code will be:

x = json.loads(y)
z1 = (x[0][0])
z2 = (x[0][1])
z3 = (x[0][2])
z4 = (x[0][3])

for i in (4,5,6):
    k= x[0].get(i)
    if k is not None:
        print(k)

Upvotes: 2

Antonio Margaretti
Antonio Margaretti

Reputation: 894

You can use x.get("key") where x is your dict. So if such key presented in your dict the data will be returned, else you will get None.

Small example:

data = x.get("some_key")
if data is not None:
    print(data)

Upvotes: 1

Related Questions