What happens if a list contains duplicates when creating a dictionary using zip and a list comprehension?


#1

Question

When creating a dictionary using a list comprehension and the zip() function, what will happen if the list for the keys contains duplicate data?

Answer

If the list passed to the zip() function contains duplicate data, the duplicate created as part of the list comprehension will be treated as an update to the dictionary and change the value associated with the key. No error will be reported. The following code example uses zip() and a list comprehension to create a dictionary of cities and temperatures. There are two entries for “New York” in the cities list. The resulting dictionary contains only one entry for “New York” with the last value 99 from the temps list.

cities = ["New York", "London", "Sydney", "New York"]
temps = [ 85, 81, 65, 99]

weather = { key:value for key,value in zip(cities, temps)}

print(weather)
# {'New York': 99, 'London': 81, 'Sydney': 65}