+ 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??
5 ответов
+ 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")}
+ 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
+ 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
+ 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 }
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