-1

With two lists of different sizes:

numbers=[1,2,3,4,5]
cities=['LA','NY','SF']

I need to get this:

result={1:'LA', 2:'NY', 3:'SF'}

I thought of doing it with:

result={number:cities[numbers.index(number)] for number in numbers if numbers.index(number)<len(cities)}

But this one-liner gets kind of long. I wonder if there is an alternative way of achieving the same goal.

EDITED LATER:

There were multiple suggestions made to use zip:

dict(zip(cities, numbers))

While it is a definitely a simpler syntax than list comprehension I've used I wonder which would be faster to execute?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

3 Answers3

3

Use zip, it will only zip upto the end of the shortest sequence

dict(zip(cities, numbers))
b10n
  • 1,166
  • 9
  • 8
1
numbers=[1,2,3,4,5]
cities=['LA','NY','SF']
dict(zip(cities,numbers))

;)

I suspect it is duplicate though - search before you post

user1941126
  • 329
  • 1
  • 8
1

The easiest is probably dict(zip(numbers,cities)) zip will stop once any of the lists ends, which is what you want.

ilmarinen
  • 4,557
  • 3
  • 16
  • 12