sorting dictionary values asc in python

Question:

I have a dictionary in python which is look like this :

{'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7'], 'Term2': [6, 'd1', 'd15', 'd46', 'd2', 'd3', 'd4'], 'Term3': [6, 'd3', 'd5', 'd43', 'd5', 'd6', 'd77'], 'Term4': [6, 'd1', 'd15', 'd46', 'd16', 'd17', 'd77'], 'Term5': [6, 'd3', 'd5', 'd43', 'd4', 'd10', 'd22'], 'Term6': [6, 'd1', 'd15', 'd46', 'd17', 'd55', 'd77'], 'Term7': [6, 'd3', 'd5', 'd43', 'd2', 'd7', 'd22'], 'Term8': [6, 'd1', 'd15', 'd46', 'd14', 'd66', 'd88'], 'Term9': [6, 'd1', 'd15', 'd46', 'd2', 'd77', 'd88'], 'Term10': [6, 'd3', 'd5', 'd43', 'd4', 'd44', 'd77'], 'Term11': [6, 'd1', 'd15', 'd46', 'd57', 'd66', 'd88'], 'Term12': [3, 'd2', 'd7', 'd66'], 'Term13': [3, 'd4', 'd44', 'd77'], 'Term14': [3, 'd55', 'd66', 'd88']}

key : values

I need to make d’s in the list sorted.. smth like :

'Term1': [6, 'd3', 'd4' 'd5', 'd6', 'd7', 'd43'] ... etc

I tried to do :

','.join(sorted(values, key=lambda x: int(x[1:])))

where values are intermediate_dictionary[term]

but i entered in infinte loop , and it’s not working …

this is my full code where I create the self.final_inverted_index:

  for term in intermediate_dictionary.keys():
        intermediate_dictionary[term].insert(0, len(intermediate_dictionary[term]))
        self.final_inverted_index[term] = intermediate_dictionary[term]
Asked By: Sam Sam

||

Answers:

One way to do this is to split the values into the int and string, sort the strings and concatenate with the int. If you use key function for sort, you can get an actual number sorting instead of standard dictionary sorting for strings:

d = {'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7']}

d = {k: [v[0]] + sorted(v[1:], key = lambda x: int(x[1:])) for k, v in d.items()}

print(d)

Non in-place version:

d = {'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7']}

new_d = {}
for k, v in d.items():
    new_d[k] = [d[k][0]] + sorted(v[1:], key = lambda x: int(x[1:]))

print(d)
Answered By: matszwecja

You can do the following:

d = {'Term1': [6, 'd3', 'd5', 'd43', 'd4', 'd6', 'd7']}

for k in d.keys():
    d[k].sort(key = lambda x: int(x[1:]) if isinstance(x, str) else 0)

Output:

{'Term1': [6, 'd3', 'd4', 'd5', 'd6', 'd7', 'd43']}
Answered By: T C Molenaar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.