+ 1
How to sum multiple values to existing key of the dictionary In one line
l = list(map(str,input().split(','))) d = {} d = {l[i+1].upper() : (int(l[i]) if l[i+1] not in d else d[l[i+1]]+int(l[i])) for i in range(0,len(l),2)} print(d) #input : 101,p,102,o,302,p,305,p Anyone, please tell me how to add value to the existing key of the dictionary in one line, in the above code value is updating to a key but it is not adding can you solve it for me, please.
15 odpowiedzi
+ 1
Make the dict with uneven keys with default value of 0.
Iterate over keys and vals while updating the value of the key.
https://code.sololearn.com/cx0i5Lmt35C7/?ref=app
+ 2
It's simple
d.__setitem__(x, y) equal d[x] = y
d.get(x, 0) the second is the default return value if not find the key x, there is a zero passed
And we can't use d[x]=y to assign the value in the list comprehension
+ 1
You means the letter is the key?
+ 1
l = list(map(str,input().split(',')))
d = {}
[d.__setitem__(l[i+1], int(d.get(l[i+1], 0)) + int(l[i])) for i in range(0, len(l), 2)]
print(d)
+ 1
Thank you so much bro 🥰
0
I need output as {'p': 708, 'o': 102}
But I getting this output {'p' : 305, 'o' :102}
0
The p value is not adding its just updating thats my problem I need add the value to p key
0
Yes the letter is the key
0
Bro It shows attribute error
0
I am not your level bro i can't understand what it is
0
Oh ok bro, but its not working bro plz check for me in compiler
0
By the way, thanks for explaining 🤗
0
It works well with your input above.
Show the wrong prompt and input output
0
Ok bro and thanks for your response bro I will check again tomorrow morning now I am going to sleep, bye bro.
0
arsh