Home > Mobile >  Update dictionary key with max value
Update dictionary key with max value

Time:12-01

I would like to create a dictionary using list of key value pairs. There are duplicate keys and I don't want the key values to be the max value.

L1 = ['a','b','b','d']
L2 = [1,3,2,4]
d = {k:v for k,v in zip(L1,L2)}
{'a': 1, 'b': 2, 'd': 4}

In the above code, the value for key 'b' is 2, I want it to stay 3 only as that is the max value.

CodePudding user response:

Maybe you could put a sort in there too, this way the highest value will be last and will be kept

d = dict(sorted(zip(L1,L2))

CodePudding user response:

L1 = ['a','b','b','d']
L2 = [1,3,2,4]
d = {}
for k,v in zip(L1,L2):
    if k not in d or d[k] < v:
        d[k] = v
print(d)

CodePudding user response:

You can use itertools.groupby for this: note: I use operator.itemgetter to get the keys/values instead of a lambda or nested for loop

from operator import itemgetter
from itertools import groupby

L1 = ['a','b','b','d']
L2 = [1,3,2,4]
get_k, get_v = itemgetter(0), itemgetter(1)
result = {k: max(map(get_v, g)) for k, g in groupby(zip(L1, L2), get_k)}

CodePudding user response:

>>> L1 = ['a','b','b','d']
>>> L2 = [1,3,2,4]
>>> from collections import defaultdict

>>> x =defaultdict(int)
>>> for a, b in zip(L1, L2):
...     if a in x:
...             x[a]=max(x[a], b)
...     else:
...             x[a]=b
... 
>>> x
defaultdict(<class 'int'>, {'a': 1, 'b': 3, 'd': 4})
>>> 
  • Related