嘿,伙计们,我有一个字典列表,它有时间戳,我想在每次迭代中按分钟分开。
现在我的字典是这样的:
{
"taco.tuesday": [
{
"timestamp": "2021-02-11 02:18:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:19:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:20:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:21:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:22:00-05:00",
"cost": 0
}
],
"macoroni.mondays": [
{
"timestamp": "2021-02-11 02:18:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:19:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:20:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:21:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:22:00-05:00",
"cost": 0
}
],
"salmon.sundays": [
{
"timestamp": "2021-02-11 02:18:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:19:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:20:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:21:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:22:00-05:00",
"cost": 0
}
],
"whatever.wednesday": [
{
"timestamp": "2021-02-11 02:18:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:19:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:20:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:21:00-05:00",
"cost": 0
},
{
"timestamp": "2021-02-11 02:22:00-05:00",
"cost": 0
}
]
}
但是我想要的是我的结果看起来像这样每分钟:
[{
"taco.tuesday": {
"timestamp": "2021-02-11 01:38:00-05:00",
"cost": 0
},
"macoroni.mondays": {
"timestamp": "2021-02-11 01:38:00-05:00",
"cost": 0
},
"salmon.sundays": {
"timestamp": "2021-02-11 01:38:00-05:00",
"cost": 0
},
"whatever.wednesday": {
"timestamp": "2021-02-11 01:38:00-05:00",
"cost": 0
}
}],
[{
"taco.tuesday": {
"timestamp": "2021-02-11 01:39:00-05:00",
"cost": 0
},
"macoroni.mondays": {
"timestamp": "2021-02-11 01:39:00-05:00",
"cost": 0
},
"salmon.sundays": {
"timestamp": "2021-02-11 01:39:00-05:00",
"cost": 0
},
"whatever.wednesday": {
"timestamp": "2021-02-11 01:39:00-05:00",
"cost": 0
}
}],
[{
"taco.tuesday": {
"timestamp": "2021-02-11 01:40:00-05:00",
"cost": 0
},
"macoroni.mondays": {
"timestamp": "2021-02-11 01:40:00-05:00",
"cost": 0
},
"salmon.sundays": {
"timestamp": "2021-02-11 01:40:00-05:00",
"cost": 0
},
"whatever.wednesday": {
"timestamp": "2021-02-11 01:40:00-05:00",
"cost": 0
}
}]
这里是我所做的,以得到我想要的结果:
e = defaultdict(dict)
for i in range(len(ts_results)):
for key, value in tables.items():
e[key]['timesamp'] = str(ts_results[i])
e[key]['cost'] = 0
实现这个解决方案的最佳方法是什么?
这是基于Ángel Igualada的答案,但纠正了他如何创建嵌套字典。
dict_by_time = {}
# for over your dict (called d here)
for k,v in d.items():
for record in v:
t = record["timestamp"]
d = dict_by_time.get(t, {})
d[k] = record
dict_by_time[t] = d
result = list(dict_by_time.values())
在不使用其他库的情况下,您可以这样做:
dict_by_time = {}
# for over your dict (called d here)
dict_by_time = {}
for k,v in d.items():
for record in v:
t = record["timestamp"]
if t not in dict_by_time:
dict_by_time[t] = {}
dict_by_time[t].update({k:record})
这将给你一个由时间戳字符串索引的字典,如果你只想要值,你可以使用:
list(dict_by_time.values())