I have a nested li below, I wanted to return a nested li with the string with and min of the int value within the same string value. Any idea?
li=[['a', 10], ['a', 20], ['a', 20], ['a', 40], ['a', 50], ['a', 60]
, ['b', 10], ['b', 20], ['b', 30], ['b', 40]
, ['c', 10], ['c', 10], ['c', 20]]
return
min_li=[['a', 10], ['b', 10], ['c', 10]]
Here is another way you can approach it. First, in a for loop, convert the nested list into a dictionary of key-value pairs, collecting all the values in a list:
li_dict = dict()
for i in li:
if i[0] in li_dict:
li_dict[i[0]].append(i[1])
else:
li_dict[i[0]] = [i[1]]
li_dict
{'a': [10, 20, 20, 40, 50, 60], 'b': [10, 20, 30, 40], 'c': [10, 10, 20]}
Next, find the minimum value for each key and convert it back into a nested list:
li_min = []
for i in li_dict:
li_min.append([i, min(li_dict[i])])
li_min
[['a', 10], ['b', 10], ['c', 10]]