comprehension | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

comprehension

https://code.sololearn.com/cd3tgiJwNyad/#py in list_4 in the above code, why am I getting a dictionary only with number 6?? plz explain??

8th Jul 2020, 5:59 AM
Mani
Mani - avatar
5 Answers
+ 2
I never got into the same situation as this so i can't be sure why this is happening.. i tought maybe the second loop is like an inside loop for the first one so it takes the last element the num comes out with which is "6" so Here is a quick fix: list_4 = {letter:nums[i%len(nums)] for i, letter in enumerate("abc")}
8th Jul 2020, 6:25 AM
Bouderbala Amine
Bouderbala Amine - avatar
+ 2
Bilbo Baggins He wants to make list_4 like {'a':1, 'b':2, 'c':3} But it comes out as {'a':6, 'b':6, 'c':6} The code i provided works fine if you want to try it out
8th Jul 2020, 6:31 AM
Bouderbala Amine
Bouderbala Amine - avatar
+ 1
Try this: print({'a':1, 'a':2, 'a':3}) # output: {'a':3} When assigning more values to the same key, only the last is held: you can22not have duplicates
8th Jul 2020, 6:21 AM
Bilbo Baggins
Bilbo Baggins - avatar
+ 1
nums = [ 1, 2, 3, 4, 5, 6 ] list_4 = { letter : num for letter, num in zip( list( 'abcdef' ), nums) } print( list_4 ) #Output: #{ 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5, 'f' : 6 }
8th Jul 2020, 7:13 AM
Ipang
0
Because {letter:num for letter in 'abcd' for num in nums } works like this... d={} for letter in 'abcd' : for num in nums: d[letter] = num So your code will do things like d['a']=1 d['a']=2 ... d['a']=6 d['b']=1 d['b']=2 ... d['b']=6 ... Finally, you will get a dictionary where keys are ("a", "b", "c", "d") and values are all 6
8th Jul 2020, 2:03 PM
李立威