[Tutor] help please

Peter Otten __peter__ at web.de
Wed Oct 10 04:44:21 EDT 2018


Michael Schmitt wrote:

> To whom it may concern:
> 
> 
> I am trying to teach myself Python and ran into a problem. This is my code

> I am getting the following error
>  for rivers in rivers.values():
> AttributeError: 'str' object has no attribute 'values'

> # prints river name
> for rivers in rivers.keys():
>     print (rivers)

Look closely at the loop above. What is the value of the "rivers" variable 
after the first iteration?

To resolve the problem simply use a different name as the loop variable.

Pro tip: When you loop over a dict you get the keys by default. So:

for river in rivers:
    print(river)

> # prints statement " The (river) is in the country of (country)
> for rivers in rivers:
>     print ("The " + rivers.keys() + "is in the country of " + 
rivers.vaules())
> 

Here's a logic (and a spelling) error: rivers.keys() comprises all rivers 
and rivers.values() all countries in the dict. You want to loop over 
rivers.items() which gives you (river, country) pairs.

Tip: print() automatically inserts spaces between its arguments. So:

for river, country in rivers.items():
    print("River", river, "is in", country)



More information about the Tutor mailing list