0

I have a dictionary:

a = {1:10,5:20,3:30,2:5}

Then I put the keys and values into lists.

key = list(a.keys())
value = list(a.values())

Then sort it

sorted(zip(key,value))
>>> [(1, 10), (2, 5), (3, 30), (5, 20)]

If I zip it again

zip(sorted(zip(key,value)))
tuple(zip(sorted(zip(key,value))))
>>> (((1, 10),), ((2, 5),), ((3, 30),), ((5, 20),))
zip(*sorted(zip(key,value)))
tuple(zip(*sorted(zip(key,value))))
>>> ((1, 2, 3, 5), (10, 5, 30, 20))

It looks like with the star(*), the keys and values are grouped separately, where without *, individual (key, value) pairs are grouped together. Can someone explain what the * does in here?

sensationti
  • 127
  • 7
  • 1
    The `*` operator in this context is for argument unpacking. This isn't specific to the `zip` function; what it does is pass each element of an iterable (in this case `sorted(zip(...))` as a separate argument to the function. Used with `zip` this gives you an easy way to "transpose" a list of lists, by passing each list as an argument to `zip`, which then recombines the elements of each list in turn. – Samwise Feb 22 '22 at 18:14

0 Answers0