首页 > 解决方案 > 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.

标签: python

解决方案


您可以iterate通过listof dicts 使用并使用defaultdictfromcollections添加具有唯一键的项目,

>>> 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'}])]

推荐阅读