'Python Dict create to own list and add all values with specific Keys in one line
I have a Loop and this Dict as output:
{2.0 : 7, 7.0 : 2}
the Key should be the same, but the Value changes everytime
now I want to create a variable for every Key in the Dict and add the value for the Key.
for k,v in labels.items():
if k == 2.0:
cars += v
elif k == 7.0:
trucks += v
else:
continue
is there a way to write this as a one Liner?
the other problem: I want to add the Value to the variable for every Key but if i use the += the Variable isn't assigned yet. Do i need to define it before or is there a better way to do it?
Solution 1:[1]
Your dictionary is called labels and may contain keys of 2.0 and 7.0
Therefore (although not a one-liner):
cars += labels.get(2.0, 0)
trucks += labels.get(7.0, 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Albert Winestein |
