合并2个列表并删除Python中的重复项

时间:2020-02-04 09:30:28

标签: python django

我有2个列表,看起来像:

temp_data:

{
  "id": 1,
  "name": "test (replaced)",
  "code": "test",
  "last_update": "2020-01-01",
  "online": false,
  "data": {
    "temperature": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...
    ]}

hum_data:

{
  "id": 1,
  "name": "test (replaced)",
  "code": "test",
  "last_update": "2020-01-01",
  "online": false,
  "data": {
    "humidity": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...
    ]}

我需要将2个列表合并为1个而不重复数据。最简单/有效的方法是什么?合并后,我想要这样的东西:

{
  "id": 1,
  "name": "test",
  "code": "test",
  "last_update": "2020-01-01",
  "online": false,
  "data": {
    "temperature": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...
    ],
    "humidity": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果未对列表hum_data和temp_data进行排序,请先对它们进行排序,然后将字典成对连接。

# To make comparisons for sorting
compare_function = lambda value : value['id']

# sort arrays before to make later concatenation easier
temp_data.sort(key=compare_function)
hum_data.sort(key=compare_function)


combined_data = temp_data.copy()

# concatenate the dictionries using the update function
for hum_row, combined_row in zip(hum_data, combined_data):
    combined_row['data'].update(hum_row['data'])

# combined hum_data and temp_data
combined_data

如果列表已经排序,则只需按字典将字典连接起来。

combined_data = temp_data.copy()

# concatenate the dictionries using the update function
for hum_row, combined_row in zip(hum_data, combined_data):
    combined_row['data'].update(hum_row['data'])

# combined hum_data and temp_data
combined_data

使用该代码,我得到了以下结果:

[
    {
    'id': 1,
    'name': 'test (replaced)',
    'code': 'test',
    'last_update': '2020-01-01',
    'online': False,
    'data': {
        'temperature': [{'date': '2019-12-17', 'value': 1}],
        'humidity': [{'date': '2019-12-17', 'value': 1}]}
    },
    {
    'id': 2,
    'name': 'test (replaced)',
    'code': 'test',
    'last_update': '2020-01-01',
    'online': False,
    'data': {
        'temperature': [{'date': '2019-12-17', 'value': 2}],
        'humidity': [{'date': '2019-12-17', 'value': 2}]}
    }
]