Last active
August 29, 2015 14:24
-
-
Save netmarkjp/babe49e8ce1d6297cf58 to your computer and use it in GitHub Desktop.
Sort nested dict with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!coding: utf-8 | |
| complex_dict = { | |
| "x": {"c1": 200, "c2": 100, }, | |
| "z": {"c1": 100, "c2": 200, }, | |
| "y": { "c2": 300, "c1": 500}, | |
| } | |
| print "# original" | |
| print complex_dict | |
| print "# only iterate" | |
| for elem in complex_dict.iteritems(): | |
| print elem | |
| print "# only sorted (sort by key)" | |
| for elem in sorted(complex_dict.iteritems()): | |
| print elem | |
| print "# sort by value's value(c1)" | |
| for elem in sorted(complex_dict.iteritems(), key=lambda val: val[1]["c1"]): | |
| print elem | |
| print "# sort by value's value(c2)" | |
| for elem in sorted(complex_dict.iteritems(), key=lambda val: val[1]["c2"]): | |
| print elem |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ➜ /tmp python sort_nested_dict.py | |
| # original | |
| {'y': {'c2': 300, 'c1': 500}, 'x': {'c2': 100, 'c1': 200}, 'z': {'c2': 200, 'c1': 100}} | |
| # only iterate | |
| ('y', {'c2': 300, 'c1': 500}) | |
| ('x', {'c2': 100, 'c1': 200}) | |
| ('z', {'c2': 200, 'c1': 100}) | |
| # only sorted (sort by key) | |
| ('x', {'c2': 100, 'c1': 200}) | |
| ('y', {'c2': 300, 'c1': 500}) | |
| ('z', {'c2': 200, 'c1': 100}) | |
| # sort by value's value(c1) | |
| ('z', {'c2': 200, 'c1': 100}) | |
| ('x', {'c2': 100, 'c1': 200}) | |
| ('y', {'c2': 300, 'c1': 500}) | |
| # sort by value's value(c2) | |
| ('x', {'c2': 100, 'c1': 200}) | |
| ('z', {'c2': 200, 'c1': 100}) | |
| ('y', {'c2': 300, 'c1': 500}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
valis tuple.(key, value)so
val[0]is the key of dict, andval[1]is the value of dict.