Home > Software engineering >  How to get a dict from a list of dict according to some threshold
How to get a dict from a list of dict according to some threshold

Time:07-21

I have a list of dicts like the one below:

list_dict = [{'Name': 'Andres', 'score': 0.17669814825057983},
 {'Name': 'Paul', 'score': 0.14028045535087585},
 {'Name': 'Feder', 'score': 0.1379694938659668},
 {'Name': 'James', 'score': 0.1348174512386322}]

I want to output another list of dict but only when sum of score is higher than a threshold=0.15

Expected output: [{'name':'Andres', 'score' : 0.1766..}]

I did this, but the code is terrible and the outuput is wrongly formatted

l = []
for i in range(len(list_dict)):
    for k in list_dict[i]['name']:
        if list_dict[i]['score']>0.15:
            print(k)

CodePudding user response:

Maybe this is what you're looking?

Actually you're very close... but just miss a few syntax. Each item in list_dict is a dictionary, so you can access and ask the score, it should not use index to get the interesting part.


new_dc = list()

for item in list_dict:            # each item is a dictionary
    if item['score'] > 0.15:      # it's better to use a meaningful variable. 
        new_dc.append(item)
        
print(new_dc)                    # [{'Name': 'Andres', 'score': 0.17669814825057983}]

Alternatively you can use List Comprehension:

output = [item for item in list_dict if item['score'] > 0.15]

assert new_dc == output    # Silence mean they're the same 

CodePudding user response:

1st approach using loop

final_list = []
for each in list_dict: #simply iterate through each dict in list and compare score
    if each['score']>0.15:
        final_list.append(each)
print(final_list)

2nd approach using list comprehension

final_list = [item for item in list_dict if item['score']>0.15]
print(final_list)
  • Related