3

I have two lists as shown below (of equal length)

cities = ['New York','Tokyo','Moscow','London']
altitudes = ['13000','12000','11000','9000']

I want to construct a dictionary as follows

mydict = {x : y for x in cities and y in altitudes}

My python interpreter says invalid syntax. why is this invalid? How would I do this?

Totem
  • 7,189
  • 5
  • 39
  • 66
liv2hak
  • 14,472
  • 53
  • 157
  • 270

4 Answers4

4
mydict = dict(zip(cities, altitudes))
Paweł Kordowski
  • 2,688
  • 1
  • 14
  • 21
2
thing = {city:altitude for city, altitude in zip(cities, altitudes)}

Comprehensions expect a single iterable (list, etc) to loop across. So, to solve it, you first need to convert your two lists into a single list, then feed that list into a comprehension that converts it to dict.

Pulling the above line apart a bit, you first use python's zip to aggregate the elements

list_of_tuples = zip(cities, altitudes)

Then you convert that into a dict:

thing = {city: alt for city, alt in list_of_tuples}

or more simply

thing = dict(list_of_tuples)
TheGrimmScientist
  • 2,812
  • 1
  • 27
  • 25
  • 1
    While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Bono Dec 03 '15 at 20:23
1

What you actually want is

mydict = dict(zip(cities, altitudes))

Doing a nested loop will give you the wrong results as it will iterate the cartesian product of the two lists as evidenced by:

>>> [ (c,a) for c in cities for a in altitudes ]
[('New York', '13000'), ('New York', '12000'), ('New York', '11000'), ('New York', '9000'), ('Tokyo', '13000'), ('Tokyo', '12000'), ('Tokyo', '11000'), ('Tokyo', '9000'), ('Moscow', '13000'), ('Moscow', '12000'), ('Moscow', '11000'), ('Moscow', '9000'), ('London', '13000'), ('London', '12000'), ('London', '11000'), ('London', '9000')]
Chad S.
  • 6,252
  • 15
  • 25
0
cities = ['New York','Tokyo','Moscow','London']
altitudes = ['13000','12000','11000','9000']
print dict(i for i in zip(cities,altitudes))

You can simply do it using this.

vks
  • 67,027
  • 10
  • 91
  • 124