我有一个大字典,但在概念上与此类似:
data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
我想按日期对嵌套的dicts进行排序。我知道如果不涉及嵌套,如何执行此操作,如下所示。我创建了一个列表,然后将键值对附加到列表中,然后排序。
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
问题是当涉及dicts中的dicts时如何执行此操作,例如我最初提到的内容:
data = {'business1': {'1/2':20, '1/4':10, '1/3':30}, 'business2': {'1/2':10, '1/4':20, '1/3':30}}
答案 0 :(得分:1)
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)])}
答案 1 :(得分:0)
你还没有说出你想要的结果,但我认为你希望它们看起来像这样:
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():
循环基本上重复dict.items()
所做的事情。所以你可以用sorted_data = list(business_data.items())
替换四行。 (在Python 2中不需要list()
调用但不会伤害任何东西,并且它在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
希望这有帮助。
答案 2 :(得分:0)
>>> 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)]}