Skip to content

Instantly share code, notes, and snippets.

@netmarkjp
Last active August 29, 2015 14:24
Show Gist options
  • Save netmarkjp/babe49e8ce1d6297cf58 to your computer and use it in GitHub Desktop.
Save netmarkjp/babe49e8ce1d6297cf58 to your computer and use it in GitHub Desktop.
Sort nested dict with Python
#!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
➜ /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})
@netmarkjp
Copy link
Author

val is tuple. (key, value)

so val[0] is the key of dict, and val[1] is the value of dict.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment