如何在Python中合并字典列表(JSON)?

时间:2017-12-14 16:22:59

标签: python json python-2.7 dictionary

我从JSON获得了两个字典列表:第一个是所有对象的列表,第二个列表是名称= Disk的对象:

list_of_dicts1 = [
 {u'id' : u'111',
  u'host' : u'host01',
  u'name' : u'Disk'},

 {u'id' : u'222',
  u'host' : u'host02',
  u'name' : u'Disk'},

 {u'id' : u'333',
  u'host' : u'host02',
  u'name' : u'CPU'}
]

list_of_dicts2 = [
 {u'id' : u'111',
  u'host' : u'host01',
  u'name' : u'Disk'},

 {u'id' : u'444',
  u'host' : u'host02',
  u'name' : u'Disk'},

 {u'id' : u'555',
  u'host' : u'host03',
  u'name' : u'Disk'}
]

我想:

仅当 list_of_dicts2 的ID更新时才会使用来自 list_of_dicts2 的ID更新 list_of_dicts1 的ID和' name'与 list_of_dicts2

匹配

如果没有具有此类'主机'的对象,则将 list_of_dicts2 中的对象添加到 list_of_dicts1 。和'名称'

结果:

list_of_dicts3 = 
    [
     {u'id' : u'111',
      u'host' : u'host01',
      u'name' : u'Disk'},

     {u'id' : u'444',
      u'host' : u'host02',
      u'name' : u'Disk'},

     {u'id' : u'333',
      u'host' : u'host02',
      u'name' : u'CPU'},

     {u'id' : u'555',
      u'host' : u'host03',
      u'name' : u'Disk'}
    ]

有什么办法吗?

3 个答案:

答案 0 :(得分:0)

你可以试试这个:

new_list_of_dicts1 = [{a:[c['id'] if c['name'] == i['name'] and c['host'] == i['host'] else i['id'] for c in list_of_dicts2][0] if a == 'id' else b for a, b in i.items()} for i in list_of_dicts1]+[i for i in list_of_dicts2 if not any(b['id'] == i['id'] for b in list_of_dicts1)]

输出:

{u'host': u'host01', u'id': u'111', u'name': u'Disk'}, {u'host': u'host02', u'id': u'222', u'name': u'Disk'}, {u'host': u'host02', u'id': u'333', u'name': u'CPU'}, {u'host': u'host02', u'id': u'444', u'name': u'Disk'}, {u'host': u'host03', u'id': u'555', u'name': u'Disk'}]

答案 1 :(得分:0)

def mergeLists(list1,list2):
    out = []
    for item1 in list1:
        #find match in list 2 which has same host and item
        match = filter(lambda x:x['host'] == item1['host'] and x['name'] == item1['name'],list2)
        if len(match) > 0:
            #if match found use entry from list 2
            out.append(match[0])
        else:
            #else use item from list 1 as it is unique
            out.append(item1)
    #lastly, add unique entries from list2
    return {v['host']+v['name']:v for v in out+list2}.values()

答案 2 :(得分:0)

您可以将这些dicts列表映射到dicts的dicts,然后将<View android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> 一个映射到另一个:

update

或更短,定义用于提取条目的函数;同样的结果:

>>> list1_as_dict = collections.OrderedDict(((d["host"],d["name"]), d) for d in list_of_dicts1)
>>> list1_as_dict.update({(d["host"], d["name"]): d for d in list_of_dicts2})
>>> list(list1_as_dict.values())
[{'name': 'Disk', 'id': '111', 'host': 'host01'},
 {'name': 'Disk', 'id': '444', 'host': 'host02'},
 {'name': 'CPU', 'id': '333', 'host': 'host02'},
 {'name': 'Disk', 'id': '555', 'host': 'host03'}]

这种复杂性将是O(n)。