0

I'm trying to iterate through the items in a list:

cities = ['San Francisco', 'Los Angeles', 'Phoenix', 'Las Vegas', 'Dallas', 'Miami', 'Washington DC', 'New York']

in order to create new dictionaries with the city name i.e. Phoenix = {}.

for city in cities:
    city = {}

But instead a dictionary named city is created:

>>> city
{}
>>> type(city)
<class 'dict'>

No dictionaries with the name of the city are created:

>>> Phoenix
Traceback (most recent call last):
  File "<pyshell#122>", line 1, in <module>
    Phoenix
NameError: name 'Phoenix' is not defined

What am I doing wrong?

usmanayubsh
  • 173
  • 1
  • 11
JDRJ
  • 11
  • 4
  • Briefly: just make a dictionary to hold those dictionaries. – TigerhawkT3 Jan 16 '16 at 19:35
  • What do you mean? Iterate through the items in a list, create some dict and use them as the variable name? – Remi Guan Jan 16 '16 at 19:36
  • Yes, that's right. Sorry I wasn't more clear. I would like the entries in the list to be the variable name for new dictionary entries. – JDRJ Jan 16 '16 at 19:37
  • Do that with a dictionary. – TigerhawkT3 Jan 16 '16 at 19:38
  • Sorry, do what with a dictionary? – JDRJ Jan 16 '16 at 19:40
  • Read the linked duplicate - its top-voted, accepted answer explains the structure. – TigerhawkT3 Jan 16 '16 at 19:47
  • @JDRJ, a variable in python cannot have space in it, so city name like ``Los Angeles`` cannot be a variable name. If all the city names are valid variable names you can check out this answer http://stackoverflow.com/questions/4859217/programmatically-creating-variables-in-python for exactly what you wanted, though as TigerhawkT3 suggested you probably shouldn't do so in the first place. – ohw Jan 16 '16 at 19:49

0 Answers0