Home > Software design >  How to group a dictionary by the first character of their key-values and sort them in ascending orde
How to group a dictionary by the first character of their key-values and sort them in ascending orde

Time:04-18

I'd like to group the dictionary by the first character of their key-value, find the minimum and maximum value and sort them in ascending order of the maximum value found.

dict = {'1,1': [1.0, 2.0], '3,1': [5.0, 8.0], '2,2': [3.0, 9.0], '2,1': [3.0, 11.0]}

The dictionary after grouping, finding the max and min value, and sort in ascending order of their maximum values should be:

dict = {'1': [1.0, 2.0], '3': [5.0, 8.0], '2': [3.0, 11.0]}

CodePudding user response:

this works but maybe someone has a more elegant answer:

dictionnary = {'1,1': [1.0, 2.0], '3,1': [5.0, 8.0], '2,2': [3.0, 9.0], '2,1': [3.0, 11.0]}
a = [i[0] for i in dictionnary.keys()]
b = dict.fromkeys(a)

for i in b:
    b[i] = []
    for j in dictionnary:
        if j[0] == i:
            if b[i]:
                if dictionnary[j][0]<b[i][0]:
                    b[i][0] = dictionnary[j][0]
                if dictionnary[j][1]>b[i][1]:
                    b[i][1] = dictionnary[j][1]
            else:
                b[i] = dictionnary[j]
b

Output:

{'1': [1.0, 2.0], '3': [5.0, 8.0], '2': [3.0, 11.0]}

Also, you shouldn't overwrite the builtin python dict

CodePudding user response:

First you can keep concatenating the lists grouped by k[0], and then take minimum and maximum of the lists:

dct = {'1,1': [1.0, 2.0], '3,1': [5.0, 8.0], '2,2': [3.0, 9.0], '2,1': [3.0, 11.0]}

output = {}
for k, v in dct.items():
    output[k[0]] = output.get(k[0], [])   v

output = {k: [min(v), max(v)] for k, v in output.items()}
print(output) # {'1': [1.0, 2.0], '3': [5.0, 8.0], '2': [3.0, 11.0]}

Alternatively, if you are willing to use defaultdict:

from collections import defaultdict # this at the beginning of the script

output = defaultdict(list)
for k, v in dct.items():
    output[k[0]]  = v

output = {k: [min(v), max(v)] for k, v in output.items()}
  • Related