Home > Mobile >  in a dictionary of list's , how to remove all elements except the max element
in a dictionary of list's , how to remove all elements except the max element

Time:09-30

In the below mentioned dictionary, which has list's as values of dictionary, how to keep only max element and remove rest of the elements and about the list containing single element has to be kept intact(since its the only element) and output the result into a new dictionary

my_dict = {'audi':[99,67,45], 'porsche':[87,76,54], 'ferrari':[76]}

CodePudding user response:

Try:

my_dict = {"audi": [99, 67, 45], "porsche": [87, 76, 54], "ferrari": [76]}

out = {k: [max(v)] for k, v in my_dict.items()}
print(out)

Prints:

{'audi': [99], 'porsche': [87], 'ferrari': [76]}

CodePudding user response:

for car, list_ in my_dict.items():
    my_dict[car] = [max(list_)]

This assumes that all values in the lists are integers.

A one liner could be:

new_dict = {car: [max(list_)] for car, list_ in my_dict.items()}
  • Related