python - Python - Inserting and Updating python dict simultaneously
问题描述
so I have a list of dicts that looks like this:
[{
'field': {
'data': 'F1'
},
'value': F1Value1,
'date': datetime.datetime(2019, 3, 1, 0, 0)
}, {
'field': {
'data': 'F2'
},
'value': F2Value1,
'date': datetime.datetime(2019, 2, 5, 0, 0)
}, {
'field': {
'data': 'F2'
},
'value': F2Value2,
'date': datetime.datetime(2019, 2, 7, 0, 0)
}]
And I want an output that looks like this:
[
{
'F1': [
{
'value': F1Value1,
'date': datetime.datetime(2019, 3, 1, 0, 0)
}
]
},
{
'F2': [
{
'value': F2Value1,
'date': datetime.datetime(2019, 2, 5, 0, 0)
},
{
'value': F2Value2,
'date': datetime.datetime(2019, 2, 5, 0, 0)
},
]
}
]
That is, I want every field.data
to be the key and have it append the value
and date
if it belongs to the same field.
Note: I want to do this WITHOUT using a for loop (apart from the loop to iterate through the list). I want to use python dict functions like update()
and append()
etc.
Any optimized solutions would be really helpful.
解决方案
您可以iterate
通过list
of dict
s 使用并使用defaultdict
fromcollections
添加具有唯一键的项目,
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>>
>>> for items in x:
... d[items['field']['data']].append({
... 'value': items['value'],
... 'date': items['date']
... })
...
>>>
>>> import pprint
>>> pprint.pprint(x)
[{'date': datetime.datetime(2019, 3, 1, 0, 0),
'field': {'data': 'F1'},
'value': 'F1Value1'},
{'date': datetime.datetime(2019, 2, 5, 0, 0),
'field': {'data': 'F2'},
'value': 'F2Value1'},
{'date': datetime.datetime(2019, 2, 7, 0, 0),
'field': {'data': 'F2'},
'value': 'F2Value2'}]
>>>
>>> pprint.pprint(list(d.items()))
[('F1', [{'date': datetime.datetime(2019, 3, 1, 0, 0), 'value': 'F1Value1'}]),
('F2',
[{'date': datetime.datetime(2019, 2, 5, 0, 0), 'value': 'F2Value1'},
{'date': datetime.datetime(2019, 2, 7, 0, 0), 'value': 'F2Value2'}])]
推荐阅读
- apache-spark - Spark 的“Dataframe API”中的“API”是什么意思?
- asp.net-mvc - 记住我的登录在服务器中不起作用,但在本地工作非常好
- javascript - 为什么Javascript点击事件不起作用
- botframework - 面向多个客户和多租户的 Microsoft Bot 身份验证
- r - 从 HTAFeatureSet 表达式数据中获取探针名称
- shell - 在 ssh 终端与 ubuntu 桌面上运行相同的命令,在 ssh 终端上无法运行?
- c# - 根据任何模型的选定属性生成输入
- c - 是否有任何可用的 mbed 以太网接口库?
- c++ - 乱码控制台输出管道 stderr 到更多
- regex - 在给定模式之前进行递归匹配