+ 7

Weird dictionary creation

Could someone explain how the code attached works exactly. It is very non-intuitive for me. https://code.sololearn.com/csURQIhxJhq2/?ref=app

2nd Oct 2022, 4:31 PM
Edward Finkelstein
Edward Finkelstein - avatar
11 Respostas
+ 8
You are using x[n] as temporary variable for loop. But x is global dictionary already so it retaining assigned values. ::( x[n] = next(arr) ) Generally temp variables gets deallocated automatically after loop.
2nd Oct 2022, 5:52 PM
Jayakrishna 🇼🇳
+ 6
Looks like a very dirty python hack đŸ˜± I would never use this monstrosity in a real program...
2nd Oct 2022, 7:11 PM
Tibor Santa
Tibor Santa - avatar
2nd Oct 2022, 10:38 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 3
Tibor Santa , Python still surprises me with the discovery of such things https://code.sololearn.com/ccnFJx595Csn/?ref=app
2nd Oct 2022, 8:30 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 3
Bob_Li , (a := [1,2,3]) and (x := {}) or [... for n, x[n] in enumerate(a, 1)] and print(x)
4th Oct 2022, 9:05 AM
Vitaly Sokol
Vitaly Sokol - avatar
+ 1
I think it just creates a key value pair based on the value of n, and then the value is the corresponding element in arr
2nd Oct 2022, 4:34 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 1
I just don’t get what the use is. Do people actually develop software with these constructs?
2nd Oct 2022, 9:07 PM
Edward Finkelstein
Edward Finkelstein - avatar
0
😎 First time I've seen this trick. It's hard to condense into a one-liner, though. I can't do it. Anyone have a solution? arr= ["a", "b", "c", "d"] ### turn this part to a one-liner ### x={} n=1 for x[n] in arr: n+=1 ########################## print(x)
4th Oct 2022, 12:33 AM
Bob_Li
Bob_Li - avatar
0
Vitaly Sokol I know about the enumerate dictionary comprehension a = ['a', 'b', 'c'] x = {i+1:v for i, v in enumerate(a)} print(x) but Edward Finkelstein's method did not use enumerate. I was wondering if there was a dictionary comprehension for that.
4th Oct 2022, 9:26 AM
Bob_Li
Bob_Li - avatar
0
This works. I wonder if use of range can be omitted? a = ['a', 'b', 'c'] x ={i+1:a[i] for i in range(len(a))} print(x)
4th Oct 2022, 10:55 AM
Bob_Li
Bob_Li - avatar
0
Ok, use index(). I think this is as short as I can get it. a = ['a', 'b', 'c'] x ={a.index(v)+1:v for v in a} print(x)
4th Oct 2022, 11:06 AM
Bob_Li
Bob_Li - avatar