I have a dict,
d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}
Is there any quick way to get a sum of the numbers in each of the lists in the dictionary?
For example, a
should return 6
, b
should return 7
, so on.
Currently, I am doing this.
for i in d:
l2=[]
for thing in d[i]:
if type(thing) == int:
l2.append(thing)
print sum(l2)
Possible for a quicker fix than having to go through each time and append the numbers to a list?
Thanks!
In this case, since the numbers are all in the 1st and 3rd positions of the lists
If you want to output as a list, use a list comprehension:
As you can see this doesn't quite match up. Manually adding the items in d gives
So why the mismatch?
It's because dictionaries are unsorted
As soon as you create d as a dictionary, it rearranges its items, and therefore outputting such a list comprehension will give you the correct sums, but you don't know which sum corresponds to which dictionary item.
This is why F.J.'s dictionary comprehension suggestion seems the best option here.
Unless you see it is workable with the list comprehension somehow?
If your dictionary having float values then the above code will not work, You will get output as 0 value.
So, For handling integers and float, you can use below code.
In comprehension way,
OR
You can use common function to check whether the given input is number or not then we can sum the values,
Here is a fairly straight forward way using a dictionary comprehension:
Or on Python 2.6 and below:
Example: