在Python中对具有非数字索引的多维字典进行排序时出现问题 [英] Issue sorting a multi-dimensional dictionary that has non-numeric indices in Python
问题描述
因此,我有一个多维字典,该字典具有用于标识内部字典的数字键,但是内部字典没有数字键.我在根据内部字典的字符串索引之一的值创建键的排序列表时遇到困难.我可能没有正确描述问题,所以下面是突出显示问题的示例脚本:
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'])
这是脚本的结果
# 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
示例字典不是我的完整用例,而是精简版本以显示问题(例如,还有另一个内部字典对该问题不重要).我之所以这样说,是因为可能有比我不知道的字典更好的数据类型,这是python的新手.
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.
如果有问题,我正在使用python 2.6.7版本.
I'm using python version 2.6.7, if it matters.
推荐答案
正如我在问题下方的注释中所述,您的表标题显示"BuyValue",并且您正在打印出售价值".根据输出的期望,我认为您在设置排序器功能时犯了一个小错误.
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.
应该是:
lambda x: my_dict[x]['market_data']['sellValue']
而不是
lambda x: my_dict[x]['market_data']['buyValue']
这篇关于在Python中对具有非数字索引的多维字典进行排序时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!