Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Dictionary Sort based on Value

graph = {
'A': [('B', 9), ('C', 7)],
'B': [('A', 5), ('D', 8), ('E', 1)],
'E': [('B', 1), ('D', 2)],
'D': [('B', 8), ('E', 2), ('F', 7), ('C', 2), ('I', 5)],
'F': [('D', 7)],
'I': [('D', 5), ('G', 14)],
'G': [('I', 14), ('C', 13)],
'C': [('A', 7), ('D', 2), ('G', 13)]}

for key, value in sorted(graph.items(), key=lambda item: (item[1], item[0])):
    print ("%s: %s" % (key, value))

I want to sort this dictionary by value of each element
For Example First item becomes
‘A’: [(‘C’, ‘7’), (‘B’, 9)],
‘B’: [(‘E’, 1),(‘A’, 5), (‘D’, 8)],
and so on

How can i do that
in python

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could iterate over the values and use list.sort to sort it in-place:

for v in graph.values():
    v.sort(key=lambda x:x[1])
print(graph)

If you want a new dictionary, you could use sorted in a dict comprehension:

out = {k: sorted(v, key=lambda x:x[1]) for k,v in graph.items()}

Output:

{'A': [('C', 7), ('B', 9)],
 'B': [('E', 1), ('A', 5), ('D', 8)],
 'E': [('B', 1), ('D', 2)],
 'D': [('E', 2), ('C', 2), ('I', 5), ('F', 7), ('B', 8)],
 'F': [('D', 7)],
 'I': [('D', 5), ('G', 14)],
 'G': [('C', 13), ('I', 14)],
 'C': [('D', 2), ('A', 7), ('G', 13)]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading