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

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}
7 Likes

4 posts were split to a new topic: Zip creates an iterator, how can we turn that into a dictionary?

Aside

def seq_sum(sequence):
  a = zip(sequence, sequence[::-1])
  return len(sequence) * sum(next(a)) // 2
print ( seq_sum(range(10)) )
45

Pared down,

def seq_sum(seq):
  return len(seq) * sum(next(zip(seq, seq[::-1]))) // 2

What does the next(a) mean here? Can’t quite get it

The sum of a sequence (common difference between terms) is given as the first and last terms added, times half the number of terms.

s = (a + z) * n / 2

Above we zip the sequence with its reverse such that the first item (next(a)) in the iterator will be a tuple containing the first and last term.

It’s just a bit of sandbox play, in reality, but it does work.