MaQ
MaQ

Reputation: 1

Why am I getting this error despite typing in the code the same as the book?

I am completely new to coding. I am going through a very basic beginner book on python and have not had any problems until now.

The practice code in the book is to make our first dictionary like

states = {
   'Alabama':  'AL',
   'Alaska':  'AK',
   'Arizona':  'AZ',
   'Arkansas':  'AR',
   'California':  'CA',
   'Colorado':  'CO',
   'Connecticut':  'CT',
 }

And then make another similar dictionary w/ capitals.

Then, we print the states, then the capitals, then the states + the capitals.

The problem is that I print the states,

for states, abbrev in states.items():
     print "%s is abbreviated %s" % (states, abbrev)

and that gives me what I want, but if I try to print the states again in any fashion

for states, abbrev in states.items():
     print "%s is abbreviated %s" % (states, abbrev)

I get the following error in my powershell, AttributeError: 'str' object has no attribute 'items'.

I am typing in the code exactly how it is in the book and still getting this error. I cannot figure it out by searching online.

So, why is this happening and how do I fix it?

Upvotes: 0

Views: 31

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

for states, abbrev in states.items():
     print "%s is abbreviated %s" % (states, abbrev)

You are using the same name (states) for both the dictionary and the key (for states ... states.items()).

After this loop runs, states is still bounded to the last key the loop visited, and in fact, you are losing access to the states dictionary.

Use a different name for the dictionary and the iteration variable, for example:

for state, abbrev in states.items():
     print "%s is abbreviated %s" % (state, abbrev)

which also makes more sense, because in each iteration the key is an individual state.

Upvotes: 1

Related Questions