[Python] Remove Duplicate Dictionaries from a list based on certain numeric value

Discussão em 'Python' iniciado por Stack, Março 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list of dictionary values which has duplicate name values. I would like to remove only the one whose value is less for the same name. For example, I have an input like below.

    [{'name': 'x', 'value': 0.6479667110413355},
    {'name': 'x', 'value': 1.0},
    {'name': 'y', 'value': 0.9413355},
    {'name': 'y', 'value': 0.9}]


    Hence, compare all the values of x and keep only that dictionary that has the highest values of x. Same goes for y. What I would like to have output is

    [{'name': 'x', 'value': 1.0},
    {'name': 'y', 'value': 0.9413355}]


    I was trying on the lines like this:

    input_list = [{'name': 'x', 'value': 0.6479667110413355}, {'name': 'x', 'value': 1.0},{'name': 'y', 'value': 0.9413355}, {'name': 'y', 'value': 0.9}]

    results = defaultdict(list)

    for element in input_list:
    for key, value in element.items():
    results[key].append(value)

    for item_key, item_value in results.items():
    results[item_key] = max(item_value)

    print(results)



    Output

    defaultdict(<class 'list'>, {'name': 'y', 'value': 1.0})



    I am missing something here. Getting only value of y and not x Can someone help on this.

    Continue reading...

Compartilhe esta Página