If I have this type of dictionary:
a_dictionary = {"dog": [["white", 3, 5], ["black", 6,7], ["Brown", 23,1]],
"cat": [["gray", 5, 6], ["brown", 4,9]],
"bird": [["blue", 3,5], ["green", 1,2], ["yellow", 4,9]],
"mouse": [["gray", 3,4]]
}
And I would like to sum from first line 3 with 6 and 23 and on next line 5 with 4 on so on so I will have when printing:
dog [32, 13]
cat [9, 15]
bird [8, 16]
mouse [3,4]
I tried a for loop of range of a_dictionary to sum up by index, but then I can't access the values by keys like:
a_dictionary[key]
But if I loop thru a_dictionary like so
for key, value in a dictionary.items():
I can't access it by index to sum up the needed values.
I would love to see how this could be approached. Thanks
CodePudding user response:
Generally, in Python you don't want to use indices to access values in lists or other iterables (of course this cannot be always applicable).
With clever use of zip()
and map()
you can sum appropriate values:
a_dictionary = {
"dog": [["white", 3, 5], ["black", 6, 7], ["Brown", 23, 1]],
"cat": [["gray", 5, 6], ["brown", 4, 9]],
"bird": [["blue", 3, 5], ["green", 1, 2], ["yellow", 4, 9]],
"mouse": [["gray", 3, 4]],
}
for k, v in a_dictionary.items():
print(k, list(map(sum, zip(*(t for _, *t in v)))))
Prints:
dog [32, 13]
cat [9, 15]
bird [8, 16]
mouse [3, 4]
EDIT:
With
(t for _, *t in v)
I'll extract the last two values from the lists (discarding the first string value)zip(*(t for _, *t in v))
will convert the last two values from each sublist to([3, 6, 23], [5, 7, 1]), ([5, 4], [6, 9]), ...
(transposing operation)Then I apply
sum()
on each of the sublist created in step 2. withmap()
The result of the
map()
is stored into a list
CodePudding user response:
You can create and sum temporary lists of an indexed element from each color using Python's list comprehension like:
for animal, colors in a_dictionary.items():
print(
animal,
[
sum([color[1] for color in colors]),
sum([color[2] for color in colors]),
]
)
CodePudding user response:
for key, value in my_dictionary.items():
sum_1, sum_2 = 0, 0
for sublist in value:
sum_1 = sublist[1]
sum_2 = sublist[2]
print(key, [sum_1, sum_2])
CodePudding user response:
a_dictionary['dog']
[['white', 3, 5], ['black', 6, 7], ['Brown', 23, 1]]
a_dictionary['dog'][0]
['white', 3, 5]
a_dictionary['dog'][0][1]
3
CodePudding user response:
This one works for me:
results = {}
sum_x = 0
sum_y = 0
for key,value in a_dictionary.items():
for i in range(len(value)):
sum_x = value[i][1]
sum_y = value[i][2]
results[key] = [sum_x,sum_y]
sum_x = 0
sum_y = 0
Output:
results
{'dog': [32, 13], 'cat': [9, 15], 'bird': [8, 16], 'mouse': [3, 4]}