Skip to content

Instantly share code, notes, and snippets.

@xsthunder
Last active June 2, 2020 10:48
Show Gist options
  • Save xsthunder/680ecd1ce122cbc42fca04a7d227b55e to your computer and use it in GitHub Desktop.
Save xsthunder/680ecd1ce122cbc42fca04a7d227b55e to your computer and use it in GitHub Desktop.
dict orders its key-value pairs in insertation order from python 3.7
# for each value(which is a dict) of input0, reorder the value dict in ascending order constructing output
import sys
assert float(sys.version[:3]) >= 3.7, """
this code only available from python version 3.7, see following for detail
https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744
dict orders its key-value pairs in insertation order
"""
input0 = {
'a':{
'a':1,
'c':3,
'b':2
},
'b':{
'b':2,
'c':3,
'a':1
},
'c':{
'a':1,
'b':2,
'c':3
},
}
output = {
'a':{
'a':1,
'b':2,
'c':3
},
'b':{
'a':1,
'b':2,
'c':3
},
'c':{
'a':1,
'b':2,
'c':3
},
}
def unroll(d):
l = d.items()
# convert dict_items to list
return [(a[0], list(a[1].items())) for a in l]
def unroll_with_dict_items(d):
l = d.items()
return [(a[0], a[1].items()) for a in l]
assert output == input0, "the order won't affect the comparing for dict"
assert output.items() == input0.items() , "dict_items comparision ignore the order"
assert unroll(input0) != unroll(output) , "now take the order into consideration"
assert unroll_with_dict_items(input0) == unroll_with_dict_items(output) , "dict_items comparision ignore the order"
def order_dict_by_value(d):
return dict(sorted(d.items(), key=lambda tp:tp[1]))
my_outputdict = dict(map(lambda tp:(tp[0], order_dict_by_value(tp[1])), input0.items()))
# before
assert unroll(output) != unroll(input0)
# after
assert unroll(output) == unroll(my_outputdict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment