繁体   English   中英

Python:按日期对嵌套字典进行排序

[英]Python: Sorting a nested dict by date

我有一个很大的意见,但在概念上与此类似:

data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}

我想按日期对嵌套字典进行排序。 我了解在不涉及嵌套的情况下如何执行此操作,如下所示。 我创建了一个列表,然后将键,值对附加到列表中,然后进行排序。

data = {'1/2':20, '1/4':10, '1/3':30}

sorted_data = []
for key,value in data.iteritems():
    temp = (key,value)
    sorted_data.append(temp)
sorted_data.sort(key = lambda item: item[0], reverse=False)
print sorted_data

问题是涉及字典中的字典时如何执行此操作,例如我首先提到的内容:

data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
from collections import OrderedDict

for k,v in data.items():
    data[k] = OrderedDict(sorted(v.items()))

print data

用户输入:

 data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}

输出:

 {'business2': OrderedDict([('1/2', 10), ('1/3', 30), ('1/4', 20)]), 'business1': OrderedDict([('1/2', 20), ('1/3', 30), ('1/4', 10)])}

您尚未说出想要的结果,但我假设您希望它们看起来像这样:

result = {'business1': [('1/2',20), ('1/3',30), ('1/4',10)],
          'business2': [('1/2',10), ('1/3',30), ('1/4',20)]}

这是我的处理方式:

result = {}
for business_name, business_data in data.iteritems():
    # The following is basically your single-data loop
    sorted_data = []
    for key,value in business_data.iteritems():
        temp = (key,value)
        sorted_data.append(temp)
    sorted_data.sort(key = lambda item: item[0], reverse=False)
    result[business_name] = sorted_data

现在,您可以保存一个步骤。 for key,value in business_data.iteritems():循环中的for key,value in business_data.iteritems():基本上是在重复dict.items()操作。 因此,您可以用sorted_data = list(business_data.items())替换四行。 list()调用在Python 2中是不必要的,但不会造成任何伤害,而在Python 3中则是必需的。由于您没有说明使用的是哪个版本,因此我将其留在了其中,以便我的答案对任何一个都适用Python 2或Python 3)。

所以我建议的最终版本是:

result = {}
for business_name, business_data in data.iteritems():
    sorted_data = list(business_data.items())
    sorted_data.sort(key = lambda item: item[0], reverse=False)
    result[business_name] = sorted_data

希望这可以帮助。

>>> data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
>>> {i:sorted(data[i].items(), key=lambda x: x[0]) for i in data}
{'business2': [('1/2', 10), ('1/3', 30), ('1/4', 20)], 'business1': [('1/2', 20), ('1/3', 30), ('1/4', 10)]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM