Explain following code? | Sololearn: Learn to code for FREE!

+5

# Explain following code?

x,*y={1:2,3:4,5:6} print(x)

3/1/2020 8:07:18 AM

Amey Godse

+12

Normally if you iterate through a dictionary, you get the keys only: for key in {1:2, 3:4, 5:6}: print(key) The same mechanism is used in the example above when unpacking the sequence of these keys to variables. x, *y = means the first element (in this case: dictionary key) is assigned to variable x, the rest of the elements to variable y. This kind of unpacking did not really make a lot of sense in the past, because dictionary keys used to be in random order, but with recent Python versions at least the keys retain the same order they were added to the dict. So at least it is more predictable what is the FIRST key.

+7

Tibor Santa great answer.. thank you!

+6

x = 1 y = [3, 5] When you add a "*" before a variable, then you are giving it all the left values.

+5

the output is 1. So only the keys count and therefore y = [3,5]

+3

Aymane Boukrouh [INACTIVE] need you here Seb TheS Tibor Santa

+3

Mirielle👽 Common for tuples but never seen in dict🤔

+2

Did yo finish the course https://www.sololearn.com/learn/Python/2485/

+2

Mirielle👽 good aspect ☝️ Oma Falk I think this is not the emoti you intended to use ;) 😂😂 no the 2nd one

+2

x, *y = {1:2, 3:4, 5:6} this means assign the first value to variable x and the remaining values to y (*y ==> all others)

+1

Oma Falk I'm sure you must have seen it in duct but you're not aware ... Are you familiar with this line def ( **kwargs ) # unpack dict