【问题标题】:Python : Extract values of 1 day from a dictionnary with datetime keys [closed]Python:使用日期时间键从字典中提取 1 天的值 [关闭]
【发布时间】:2015-08-03 13:36:52
【问题描述】:
我有一个以日期时间为键、以数字为值的字典。
dict = {'08/07/2015 01:15':'3', '08/07/2015 08:15':'5',
'09/07/2015 07:15':'4', '09/07/2015 10:30':'8'}
我想提取每天的值。例如,在 09/07/2015 我想要这个结果:
result = {'09/07/2015 07:15': '4', '09/07/2015 10:30': '8'}
或
result = [4, 8]
感谢您的帮助。
【问题讨论】:
标签:
python
datetime
dictionary
【解决方案1】:
>>> filter(lambda x: x[0:10] == "09/07/2015", dict)
['09/07/2015 10:30', '09/07/2015 07:15']
提示:不要使用dict 作为变量名。它已经被python使用了。
还有一个扩展版本:
>>> filtered = {}
>>> for date, value in dict.iteritems():
... if date.startswith("09/07/2015"):
... filtered[date] = value
...
>>> filtered
{'09/07/2015 10:30': '8', '09/07/2015 07:15': '4'}
【解决方案2】:
如果我理解了这个问题,那么如果不检查你的字典中的所有键是不可行的。
dict 键是无序的集合,并且因为它们没有顺序,所以无法在单个操作中获取键的“范围”。
由于您将时间散列到您的密钥中,因此 2015 年 9 月 7 日可能有任意数量的密钥,因此无法在不查看的情况下检索每个密钥。
根据您要完成的工作,您可能会考虑使用 dicts 的 dict,其中顶部的 dict 是按日期的,内部的是按时间的;例如
dict = {
"08/07/2015": { "01:15":"3" },
"09/07/2015": { "07:15":"4", "10:30":"8" }
}
或某种有序的数据类型,如数组(这会花费您查找时间但需要更少的空间)。
【解决方案3】:
您需要迭代键并将键值与所需日期进行比较。
例如:
>>> sample = {"08/07/2015 01:15":"3", "08/07/2015 01:15":"5", "09/07/2015 07:15":"4", "09/07/2015 10:30":"8"}
>>> filtered = dict((x,y) for (x,y) in sample.items() if x.startswith('09/07/2015'))
>>> filtered
{'09/07/2015 10:30': '8', '09/07/2015 07:15': '4'}
>>> filtered.values()
['8', '4']