我有以下字典:
myList= {'Green Cars': {'April': 11455.0, 'March': 12210, 'February': 2559, 'August': 1439, 'July': 4921, 'January': 340, 'December': 340, 'November': 340, 'October': 306, 'September': 6},
'Yellow cars': {'April': 192914, 'March': 20187, 'February': 20994, 'January': 230625, 'December': 208422, 'November': 17914, 'October': 170835, 'September': 185357, 'July': 226697, 'May': 1852, 'August': 22096},
'Red Cars': {'April': 159, 'March': 1400, 'February': 2620, 'January': 237, 'August': 2959, 'July': 6943},...
如何按月分类每个主键(" Green Cars"," Yellow Cars"," Red Cars"等等?
我已经看过如何通过内部字典对字典进行排序,其中辅助键是相同的,但不是在更改时。
最后,我将这些全部排序,以便通过matplotlib为不同的汽车按月获得图表。
答案 0 :(得分:3)
您有两个问题:对dicts的嵌套字典进行排序,并在dict中维护已排序的结果。在Python中,dicts是无序的。
要对您用作示例的词典的词典进行排序:
import calendar
months=list(calendar.month_name) # use a dict if you have lots of data...
myDictODicts= {'Green Cars': {'April': 11455.0, 'March': 12210, 'February': 2559, 'August': 1439, 'July': 4921, 'January': 340, 'December': 340, 'November': 340, 'October': 306, 'September': 6},
'Yellow cars': {'April': 192914, 'March': 20187, 'February': 20994, 'January': 230625, 'December': 208422, 'November': 17914, 'October': 170835, 'September': 185357, 'July': 226697, 'May': 1852, 'August': 22096},
'Red Cars': {'April': 159, 'March': 1400, 'February': 2620, 'January': 237, 'August': 2959, 'July': 6943}}
for k in myDictODicts:
print(k, sorted(myDictODicts[k].items(), key=lambda t: months.index(t[0])))
打印:
Green Cars [('January', 340), ('February', 2559), ('March', 12210), ('April', 11455.0), ('July', 4921), ('August', 1439), ('September', 6), ('October', 306), ('November', 340), ('December', 340)]
Yellow cars [('January', 230625), ('February', 20994), ('March', 20187), ('April', 192914), ('May', 1852), ('July', 226697), ('August', 22096), ('September', 185357), ('October', 170835), ('November', 17914), ('December', 208422)]
Red Cars [('January', 237), ('February', 2620), ('March', 1400), ('April', 159), ('July', 6943), ('August', 2959)]
您可以使用元组列表或直接使用它们重新创建字典。
使用Python 3.6,您可以将已排序的元组列表转换回dict,以保持其插入顺序。您还可以使用OrderedDict作为dict
对代码的其余部分显示的内容。
示例:
from collections import OrderedDict
nd={}
for k in myDictODicts:
nd[k]=OrderedDict(sorted(myDictODicts[k].items(), key=lambda t: months.index(t[0])))
>>> nd
{'Green Cars': OrderedDict([('January', 340), ('February', 2559), ('March', 12210), ('April', 11455.0), ('July', 4921), ('August', 1439), ('September', 6), ('October', 306), ('November', 340), ('December', 340)]), 'Yellow cars': OrderedDict([('January', 230625), ('February', 20994), ('March', 20187), ('April', 192914), ('May', 1852), ('July', 226697), ('August', 22096), ('September', 185357), ('October', 170835), ('November', 17914), ('December', 208422)]), 'Red Cars': OrderedDict([('January', 237), ('February', 2620), ('March', 1400), ('April', 159), ('July', 6943), ('August', 2959)])}