How do I use python to turn two lists into a dictionary, and the value is the maximum value

Viewed 33

I have two lists here

L = ["a","b","b","c","c","c"]
L_02 = [1,3,2,4,6,""]

I want to turn two lists into a dictionary, and the value is the maximum value

dic = {"a":1,"b":3,"c":6}

how can I do this?

2 Answers

We can first get the indices of each element in the list, get the corresponding values in the second list, and find the maximums and make a dictionary.

dic = {}
for element in set(L):
    indices = [i for i, x in enumerate(L) if x == element]
    corresponding = []
    for i in indices:
        if type(L_02[i]) == int:
            corresponding.append(L_02[i])
    value = max(corresponding)
    dic[element] = value
L = ["a","b","b","c","c","c"]
L_02 = [1,3,2,4,6,""]
return_dict = {}
for item1, item2 in list(zip(L,L_02)):
    if item1 not in return_dict:
        return_dict[item1] = item2
    elif isinstance(item2,int) and return_dict[item1] < item2:
        return_dict[item1] = item2
print(return_dict) 

Output:

{'a': 1, 'b': 3, 'c': 6}
Related