+ 2

Please explain why three?

numbers=['one','two','three','four'] num_dict={x[0]: x for x in numbers} print(num_dict['t'])

29th Aug 2019, 11:29 AM
Navneet
Navneet - avatar
2 Answers
+ 2
In the second line {x[0]: x for x in numbers}. Since string can be act like a list of characters. It would return a dictionary like this: { 'one'[0]: 'one', 'two'[0]: 'two', 'three'[0]: 'three', 'four'[0]: 'four' } When there is duplicate key in a dictionary, use the last value. So num_dict['t'] would return 'three'.
29th Aug 2019, 12:26 PM
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż - avatar
+ 2
The for loop runs the values of the numbers list and it adds to a dictionary the first letter of every value as a key and the value itself as a value then the dictionary looks this way: {'o':'one', 't':'three', 'f', 'four'}
29th Aug 2019, 12:22 PM
Eliya Ben Baruch
Eliya Ben Baruch - avatar