2014-11-03 19 views
1

排序嵌套字典我有一個大字典,但在概念上與此類似的:的Python:按日期

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}} 
+0

你打算做任何特定的語言? – 2014-11-03 03:18:51

+0

是的,Python。謝謝! – Steve 2014-11-03 03:20:42

+0

字典是無序的。你爲什麼要分類?您可能正在尋找一個列表 – inspectorG4dget 2014-11-03 03:26:39

回答

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 

希望這有助於。

+0

順便說一句,請注意,如果您的日期看起來像您的示例代碼(即在10之前的幾天或幾個月內有單個數字的字符串),排序將在'1/2'之前放置'1/10'。如果要字符串比較以正確比較日期,則需要將日期轉換爲像「yyyy-mm-dd」這樣的格式,並且具有固定的數字位數(以及年月日訂單)。 – rmunn 2014-11-03 03:30:54

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)])} 
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)]}