简体   繁体   中英

python: how to access values in nested dictionaries using loops

Given the following dictionary in python.

dict = {'site1': {'status': 200}, 'site2': {'status': 200}, 'site3': {'status': 200}}

How can I iterate and access the values of a sub dictionary?

for sub in dict.items():
    print(sub["status"])

gives error: tuple indices must be integers or slices, not str

Desired outcome: print 3 strings indicating site status for each sub dict.

items() returns a tuple of (key, value), so for loop should like this:

dct = {'site1': {'status': 200}, 'site2': {'status': 200}, 'site3': {'status': 200}}

for key, value in dct.items():
    print(value['status'])

Out:

200
200
200

dict.items() returns iterable of tuple pairs (key, value) . In here you want to further index a value , so you should either do:

for sub in dict.values():
    print(sub["status"])

to iterate values only.

Or:

for key, sub in dict.items():
    print(sub["status"])

to unpack the tuple (that's what one usually does when dealing with dict.items() ).

Of course you could also index the tuple first - sub[1]["status"] but it's not as readable.


PS You should never name your dicts just dict (nor lists list ) - it's a build-in name used to denote the type. Changing it might introduce bugs later on.

for sub in dict.values():
  print(sub)
#that will gives you list of dictionaries
{'status': 200} {'status': 200} {'status': 200} 

Now to print key values

for sub in dict.values():
   print(sub['status'])

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