+ 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
11 ответов
+ 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.
+ 6
Looks like a very dirty python hack 😱
I would never use this monstrosity in a real program...
+ 3
Tibor Santa , Python still surprises me with the discovery of such things
https://code.sololearn.com/ccnFJx595Csn/?ref=app
+ 3
Bob_Li ,
(a := [1,2,3]) and (x := {}) or [... for n, x[n] in enumerate(a, 1)] and print(x)
+ 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
+ 1
I just don’t get what the use is. Do people actually develop software with these constructs?
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)
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.
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)
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)