Atila
Atila

Reputation: 81

How to sort dictionary with list values?

How to sort the below dictionary?

dict_val = {"A": ["2", "1"], "B": ["6", "4"]}

Output:

{"A": ["1", "2"], "B": ["4", "6"]}

Upvotes: 0

Views: 46

Answers (1)

Emma
Emma

Reputation: 27723

I'm guessing that we'd be having int in our lists, which in that case,

dict_val = {"A": ["2", "1"], "B": ["6", "4"]}

for k,v in dict_val.items():
    dict_val[k].sort(key=int)

might be just one way to do so.

Using sorted would be another option:

for k,v in dict_val.items():
    dict_val[k]=sorted(dict_val[k])

Output

{'A': ['1', '2'], 'B': ['4', '6']}

Upvotes: 1

Related Questions