comprehension | Sololearn: Learn to code for FREE!


comprehension in list_4 in the above code, why am I getting a dictionary only with number 6?? plz explain??

7/8/2020 5:59:51 AM


5 Answers

New Answer


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")}


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


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


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 }


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