+ 3

Python question about dictionary

Just played a confusing Python code on SoloLearn: arr = ['b', 'c', 'd'] x = {1:'a'} n = 1 for x[n] in arr: n+= 1 print (x) Answer is {1: 'b', 2: 'c', 3: 'd'} I don't understand how the dictionary x get modified in this process, anyone could enlighten me?

18th Feb 2020, 3:27 AM
Xiang Song
Xiang Song - avatar
6 odpowiedzi
+ 5
if u had for i in array: ... you would assign each element of array to i. now here we have x[n] instead of i and n = 1. in the first loop you assign first element ( not to i but ) to x[1]. in the next loop the 2nd element to x[2]...
18th Feb 2020, 6:17 AM
Oma Falk
Oma Falk - avatar
+ 1
Oma Falk Thank you for the explanation. I totally understand now, it’s such a beautiful way to creat dictionary!
18th Feb 2020, 12:49 PM
Xiang Song
Xiang Song - avatar
+ 1
WhyFry check Oma’s explaination, in each of for loop, there was actullay a “x[n] =...” happened.
18th Feb 2020, 12:52 PM
Xiang Song
Xiang Song - avatar
+ 1
Xiang Song Thanks for asking this I was curios too!!
18th Feb 2020, 1:17 PM
Aditya Singh Chauhan
Aditya Singh Chauhan - avatar
0
Aditya Singh Chauhan yep....ine of my favorite posts the last weeks
18th Feb 2020, 2:14 PM
Oma Falk
Oma Falk - avatar