Python merge lists by common element

前端 未结 6 1511
梦毁少年i
梦毁少年i 2021-01-26 09:24

Im trying to merge two lists that have a common thing between them (in that case is a the id parameter). I have something like this:

list1=[(id1,host1

6条回答
  •  礼貌的吻别
    2021-01-26 10:03

    from collections import defaultdict
    list1 = [("id1","host1"),("id2","host2"),("id1","host5"),("id3","host4"),("id4","host6"),("id5","host8")]
    list2 = [("id1","IP1"),("id2","IP2"),("id3","IP3"),("id4","IP4"),("id5","IP5")]
    host = defaultdict(list)
    IP4id = {}
    for k, v in list2:
        IP4id[v] = {"id" : k, "host" : []}
    
    for k, v in list1:
        host[k].append(v)
    
    for item in IP4id:
        IP4id[item]["host"] = host[IP4id[item]["id"]]
    print IP4id
    

提交回复
热议问题