+ 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.

9th Jan 2022, 5:04 PM
Anna Hari
Anna Hari - avatar
15 Respuestas
+ 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
9th Jan 2022, 6:13 PM
John
+ 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
9th Jan 2022, 5:34 PM
FanYu
FanYu - avatar
+ 1
You means the letter is the key?
9th Jan 2022, 5:11 PM
FanYu
FanYu - avatar
+ 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)
9th Jan 2022, 5:22 PM
FanYu
FanYu - avatar
+ 1
Thank you so much bro 🥰
9th Jan 2022, 6:16 PM
Anna Hari
Anna Hari - avatar
0
I need output as {'p': 708, 'o': 102} But I getting this output {'p' : 305, 'o' :102}
9th Jan 2022, 5:18 PM
Anna Hari
Anna Hari - avatar
0
The p value is not adding its just updating thats my problem I need add the value to p key
9th Jan 2022, 5:18 PM
Anna Hari
Anna Hari - avatar
0
Yes the letter is the key
9th Jan 2022, 5:19 PM
Anna Hari
Anna Hari - avatar
0
Bro It shows attribute error
9th Jan 2022, 5:28 PM
Anna Hari
Anna Hari - avatar
0
I am not your level bro i can't understand what it is
9th Jan 2022, 5:28 PM
Anna Hari
Anna Hari - avatar
0
Oh ok bro, but its not working bro plz check for me in compiler
9th Jan 2022, 5:35 PM
Anna Hari
Anna Hari - avatar
0
By the way, thanks for explaining 🤗
9th Jan 2022, 5:36 PM
Anna Hari
Anna Hari - avatar
0
It works well with your input above. Show the wrong prompt and input output
9th Jan 2022, 5:41 PM
FanYu
FanYu - avatar
0
Ok bro and thanks for your response bro I will check again tomorrow morning now I am going to sleep, bye bro.
9th Jan 2022, 5:44 PM
Anna Hari
Anna Hari - avatar
0
arsh
11th Jan 2022, 12:51 PM
عرشیا قاسمیان