Home > Enterprise >  Merge two lists into a dictionary with only the maximums from second list for keys from first list p
Merge two lists into a dictionary with only the maximums from second list for keys from first list p

Time:02-21

imaginary data:

list_1 = ["Harry", "Harry", "Harry", "Ron" , "Ron" , "Ron", "Fred","Fred, "George", "Jerry"]

list_2 = [158, 167, 145, 177, 187, 190, 167, 187, 190, 177]

So, in my list_2(height) corresponds to the list_1 in the same order. And I am trying to just extract the maximum height for each name in a combined dictionary.

Such that my output should give me:

combined_dictionary = {"Harry" : 167, "Ron" : 190, "Fred":187, "George":190,"Jerry":177}

my code is: combined_dictionary = dict(zip(list_1, list_2) this gets me a combined dictionary but not with the maximum height.

Then, I tried: max(combined_dictionary.values()) but that obviously just gets the single value from the (flawed) combined dictionary I already created above.

I know I am missing something obvious here, can't figure out what

CodePudding user response:

This is the simplest approach, I think:

>>> combined_dictionary = {}
>>> for name, height in zip(list_1, list_2):
...     combined_dictionary[name] = max(combined_dictionary.get(name, 0), height)
...
>>> combined_dictionary
{'Harry': 167, 'Ron': 190, 'Fred': 187, 'George': 190, 'Jerry': 177}

If you wanted to do something with all the heights other than get the max, a better approach might be to start by accumulating them into a dict of lists:

>>> combined_dictionary = {name: [] for name in list_1}
>>> for name, height in zip(list_1, list_2):
...     combined_dictionary[name].append(height)
...
>>> combined_dictionary = {name: max(heights) for name, heights in combined_dictionary.items()}
>>> combined_dictionary
{'Harry': 167, 'Ron': 190, 'Fred': 187, 'George': 190, 'Jerry': 177}

CodePudding user response:

You need to iterate over each element in the list and use max() to retain the highest height seen:

import math

list_1 = ["Harry", "Harry", "Harry", "Ron" , "Ron" , "Ron", "Fred","Fred", "George", "Jerry"]
list_2 = [158, 167, 145, 177, 187, 190, 167, 187, 190, 177]

max_values = {}
for name, height in zip(list_1, list_2):
    max_values[name] = max(height, max_values.get(name, -math.inf))

# Prints {'Harry': 167, 'Ron': 190, 'Fred': 187, 'George': 190, 'Jerry': 177}
print(max_values)

CodePudding user response:

you can achieve what you want with:

heights_dict = {}
for i, item in enumerate(list_1):
    if item not in heights_dict:
        heights_dict[item] = list_2[i]
        continue 
    if heights_dict[item] < list_2[i]:
        heights_dict[item] = list_2[i]

print(heights_dict)

{'Harry': 167, 'Ron': 190, 'Fred': 187, 'George': 190, 'Jerry': 177}
  • Related