So I have a multi-dimensional dictionary that has a numeric key identifying an inner dictionary, but the inner dictionary does not have numeric keys. I’m having difficulty creating a sorted list of keys based on the value of one of the inner dictionary’s string indices. I might not have described the issue properly, so here is an example script highlighting the issue:
#! /usr/bin/python
my_dict = {
12608: {
'market_data': {
'sellVolume': 69210, 'buyValue': 296.20999999999998,
'sellValue': 523.20000000000005, 'buyVolume': 9210899
}
},
24513: {
'market_data': {
'sellVolume': 42148, 'buyValue': 548.95000000000005,
'sellValue': 890.0, 'buyVolume': 11213386
}
},
12773: {
'market_data': {
'sellVolume': 383000, 'buyValue': 609.54999999999995,
'sellValue': 799.98000000000002, 'buyVolume': 10285288
}
},
24486: {
'market_data': {
'sellVolume': 1314250, 'buyValue': 99.780000000000001,
'sellValue': 425.0, 'buyVolume': 14690060
}
},
2801: {
'market_data': {
'sellVolume': 247577, 'buyValue': 348.98000000000002,
'sellValue': 518.94000000000005, 'buyVolume': 10325916
}
}
}
d_sorted = sorted(my_dict, key=lambda \
x: my_dict[x]['market_data']['buyValue'], reverse=True)
print "key\tbuyValue"
for key in d_sorted:
print "%d\t%.2f" % (key, my_dict[key]['market_data']['sellValue'])
And here are the results of the script
# Results:
# key buyValue
# 12773 799.98
# 24513 890.00
# 2801 518.94
# 12608 523.20
# 24486 425.00
# Expected:
# key buyValue
# 24513 890
# 12773 799.98
# 12608 523.2
# 2801 518.94
# 24486 425
The example dictionary is not my full use-case, but a stripped down version to show the problem (there’s another inner-dictionary that was unimportant to the issue for example). I mention this because there might be a better data type to use than dictionary that I’m unaware of, being new to python.
The question here was instrumental in getting me this far, and the main difference I see is that my second dimension does not use integer keys.
I’m using python version 2.6.7, if it matters.
As I said in the comment below the question, your table header says “BuyValue” and you are printing “Sell value”. Going by the output what you expect, I think you just made a small mistake in setting the sorter function.
It should be:
and not