0

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.

1
  • for site_name, data in dict.items():... Commented Oct 23, 2020 at 18:39

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1
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'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.