Brendan Brendan - 3 years ago 53
Python Question

Compare Items In A List Of Nested Dicts And Perform Simple Arithmetic Operations

How can I put the list "image_list" into a function measure_accuracy then have it return a number of times actual and predicted are the same? In this case, it would return 3.

List:

image_list = [
{ 'path':'1.jpg', 'actual':{'dog'}, 'predicted':{'dog'} },
{ 'path':'2.jpg', 'actual':{'dog'}, 'predicted':{'cat'} },
{ 'path':'3.jpg', 'actual':{'cat'}, 'predicted':{'cat'} },
{ 'path':'4.jpg', 'actual':{'cat'}, 'predicted':{'dog'} },
{ 'path':'5.jpg', 'actual':{'dog'}, 'predicted':{'dog'} }
]


So what I want is to compare each item in the list and if then if the two items are the same add to a variable then in the end return that variable.
I just do not know the code to get there.

I thought maybe something like

for actual, predicted in image_list:
if actual == predicted:
count = count + 1

Answer Source
In [7]: sum(x['actual'] == x['predicted'] for x in image_list)
Out[7]: 3

so:

def measure_accuracy(image_list):
    return sum(x['actual'] == x['predicted'] for x in image_list)

total = measure_accuracy(image_list)
average = total / len(image_list)

A brief explanation of what's happening here:

x['actual'] == x['predicted']

Evaluates to either True or False. In Python, True == 1 and False == 0, so we're getting 1 each time the predicted value is equal to the actual value, otherwise 0. So our list would look like this:

[1, 0, 1, 0, 1]

then we use the sum function to add them all together to get 3.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download