I have a dictionary with 2 keys (dog and cat):
d = {'dog': [['4.1', '7.0', 'dog'], ['1.2', '3.4', 'dog']], 'cat': [['1', '8.2', '5.501', 'cat'], ['6.5', '8', '9.1', 'cat']]}
I need to find the average of the nested lists of the values for each key. For example, for dog, I need to find the average of 4.1 and 1.2, as well as 7.0 and 3.4.
The problem I'm having is that the nested lists have the numbers as strings. I figured I need an outer while loop to control column number, and then an inner while loop to control row number, however I don't know how to set this up. How do I access the inner list for each key and then access the deeper lists to find the averages?
for keys in d:
for values in d[keys]:
(2 while loops here)
Is this how I would go about it?
Thanks.
Assuming value in dictionary contains list of only two elements (which are again lists):
d = {'dog': [['4.1', '7.0', 'dog'], ['1.2', '3.4', 'dog']], 'cat': [['1', '8.2', '5.501', 'cat'], ['6.5', '8', '9.1', 'cat']]}
avg_dict = {}
for key in d:
avg_list = []
i = 0
while (i < len(d[key][0]) - 1):
avg_list.append((float(d[key][0][i]) + float(d[key][1][i])) /2.0)
i += 1
avg_dict[key] = avg_list
print(avg_dict)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments