Python 按键排序字典-解包错误
我有一本字典,钥匙上有时间戳。基本上,我想根据时间戳对字典进行排序;因此,我可以获取对应于“第一个”时间戳的字典值 我试过:Python 按键排序字典-解包错误,python,sorting,dictionary,Python,Sorting,Dictionary,我有一本字典,钥匙上有时间戳。基本上,我想根据时间戳对字典进行排序;因此,我可以获取对应于“第一个”时间戳的字典值 我试过: from __future__ import print_function from collections import OrderedDict from datetime import datetime def _fetch_ts(name): return datetime.strptime(name[-13:], '%Y%m%d_%H%M') inc
from __future__ import print_function
from collections import OrderedDict
from datetime import datetime
def _fetch_ts(name):
return datetime.strptime(name[-13:], '%Y%m%d_%H%M')
incoming_dict = {'20170410_1133': 'A', '20170412_1133': 'B'}
print("starting with: {}".format(incoming_dict))
sorted_dict = OrderedDict(sorted(incoming_dict, key=_fetch_ts))
print("gives : {}".format(incoming_dict))
print("should be A or B: {}".format(sorted_dict.values()[0]))
但那是印刷品
starting with: {'20170410_1133': 'A', '20170412_1133': 'B'}
Traceback (most recent call last):
File "test.py", line 13, in <module>
sorted_dict = OrderedDict(sorted(incoming_dict, key=_fetch_ts))
File "/usr/lib/python2.7/collections.py", line 69, in __init__
self.__update(*args, **kwds)
File "/usr/lib/python2.7/_abcoll.py", line 571, in update
for key, value in other:
ValueError: too many values to unpack
以以下开头:{'20170410_1133':'A','20170412_1133':'B'}
回溯(最近一次呼叫最后一次):
文件“test.py”,第13行,在
排序的\u dict=OrderedDict(排序的(传入的\u dict,键=\u获取的\u ts))
文件“/usr/lib/python2.7/collections.py”,第69行,在__
自我更新(*args,**kwds)
文件“/usr/lib/python2.7/_abcoll.py”,第571行,更新中
对于键,其他中的值:
ValueError:要解压缩的值太多
那么我在这里做错了什么呢?您应该使用incoming_dict.items()从incoming_dict解包值对
OrderedDict(sorted(incoming_dict.items(), key=_fetch_ts))
如前所述,您还需要修改
\u fetch\u ts
,但是您可以轻松地引用名称[0][13://code>您可以通过提前排序并将其重建为元组列表来重建OrderedICT
比如:
您可以对字典键进行排序,而不是对键值对进行排序。使用sorted(incoming\u dict.items(),…)
。您还需要更改\u fetch\ts
。这是一个很好的细节。但我认为我同意第一种解决方案;我觉得这更有可读性。
from __future__ import print_function
from collections import OrderedDict
from datetime import datetime
def _fetch_ts(name):
val = datetime.strptime(name[-13:], '%Y%m%d_%H%M')
return val
incoming_dict = {'20170410_1133': 'A', '20170412_1133': 'B'}
print("starting with: {}".format(incoming_dict))
print(sorted(incoming_dict, key=_fetch_ts))
sorted_dict = OrderedDict([(x,incoming_dict[x]) for x in sorted(incoming_dict, key=_fetch_ts)])
print("gives : {}".format(incoming_dict))
print("should be A or B: {}".format(sorted_dict.values()[0]))