How to join 2 lists of dicts in python?

后端 未结 4 1575
醉梦人生
醉梦人生 2021-01-12 23:14

I have 2 lists like this:

l1 = [{\'a\': 1, \'b\': 2, \'c\': 3, \'d\': 4}, {\'a\': 5, \'b\': 6, \'c\': 7, \'d\': 8}]

l2 = [{\'a\': 5, \'b\': 6, \'e\': 100},          


        
4条回答
  •  盖世英雄少女心
    2021-01-12 23:25

    Simple list operations would do the thing for you as well:

    l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
    l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]
    l3 = []
    
    for i in range(len(l1)):
        for j in range(len(l2)):
            if l1[i]['a'] == l2[j]['a'] and l1[i]['b'] == l2[j]['b']:
                l3.append(dict(l1[i]))
                l3[i].update(l2[j])
    

提交回复
热议问题