Home > Back-end >  How to compare items with values of list of dict in python
How to compare items with values of list of dict in python

Time:04-14

I have a output list of dicts:

# outList
[{'Current NAV': 22, 'status': 'Confirmed'},
 {'Current NAV': 25, 'status': 'Confirmed'},
 {'Current NAV': 31, 'status': 'Confirmed'},
 {'Current NAV': 55, 'status': 'Rejected'},
 {'Current NAV': 65, 'status': 'Rejected'},
 {'Amount Requested': 50, 'status': 'Confirmed'},
 {'Amount Requested': 55, 'status': 'Confirmed'},
 {'Amount Requested': 60, 'status': 'Confirmed'},
 {'Amount Requested': 80, 'status': 'Rejected'},
 {'Amount Requested': 90, 'status': 'Rejected'}]

Above data contains info about the attribute i.e. Current NAV Amount Requested, its value and its status. I have a below input list of dict:

# fieldValList
[{'name': 'Current NAV', 'value': 33},
 {'name': 'Amount Requested', 'value': 45}]

I have to compare the value of Current NAV and Amount Requested from fieldValList with outList so that I get the output of how many values from outList are closer to Current NAV value i.e. 33. In this case it is 22, 25, 31 are closer to 33 while values 55, 65 are far from it and thus Confirmed status becomes 3/5 while Rejected becomes 2/5. Similarly for Amount Requested 55, 65, 50 are closer to 45 while 80, 90 are far from it and thus Confirmed status becomes 3/5 while Rejected becomes 2/5.

I am not getting any ideas on how I can proceed to build a logic for this. Please any suggestions thanks.

CodePudding user response:

Similarly for Amount Requested 55, 65, 50 are closer to 45 while 80, 90 are far from it and thus Confirmed status becomes 3/5 while Rejected becomes 2/5.

Does it mean you want to get fractions of 'status' from 'outList' for each name from 'fieldValList'? If so then this is a tip:

from fractions import Fraction

# note that the list has been mutated
outList =[
    {'Current NAV': 22, 'status': 'Confirmed'},
    {'Current NAV': 25, 'status': 'Confirmed'},
    {'Current NAV': 31, 'status': 'Confirmed'},
    {'Current NAV': 55, 'status': 'Rejected'},
    {'Current NAV': 65, 'status': 'Rejected'},
    {'Amount Requested': 50, 'status': 'Confirmed'},
    {'Amount Requested': 55, 'status': 'Confirmed'},
    {'Amount Requested': 80, 'status': 'Rejected'},
    {'Amount Requested': 90, 'status': 'Rejected'}]
fieldValList = [
    {'name': 'Current NAV', 'value': 33},
    {'name': 'Amount Requested', 'value': 45}]

for i in fieldValList:
    n = [j['status']=='Confirmed' for j in outList if i['name'] in j]
    print(f"name: {i['name']}, Confirmed: {Fraction(sum(n), len(n))}")

>>> out
'''
name: Current NAV, Confirmed: 3/5
name: Amount Requested, Confirmed: 1/2

Otherwise, you should, as already mentioned, define the criteria for what is considered as "closer".

  • Related