0
lst1 = [
    {'mem': '20.0', 'name': 'p1', 'cpu': '20.0'}, 
    {'mem': '20.0', 'name': 'p2', 'cpu': '20.0'},
    {'mem': '20.0', 'name': 'p3', 'cpu': '20.0'}, 
    {'mem': '20.0', 'name': 'p4', 'cpu': '20.0'}
]

lst2 = [
    {'pid': 814, 'name': 'p1'},
    {'pid': 999, 'name': 'p2'},
    {'pid': 1006, 'name': 'p3'},
    {'pid': 1152, 'name': 'p4'}
]

I need to merge above two list into single list i.e.

lst3 = [
    {'mem': '20.0', 'name': 'p1', 'cpu': '20.0', 'pid':814}, 
    {'mem': '20.0', 'name': 'p2', 'cpu': '20.0','pid':999},
    {'pid': 1006, 'mem': '20.0', 'name': 'p3', 'cpu': '20.0'},
    {'pid': 1152,'mem': '20.0', 'name': 'p4', 'cpu': '20.0'}
]

I have tried doing it in below way

lst3 = list()
test = dict()
for f,b in zip(lst1,lst2):
    test = f.copy()
    test.update(b)
    #print test
    lst3.append(test)

print lst3

Please let me know is there any easy method or more pythonic way to do this

3

2 Answers 2

2

Just use zip and merge, as long as both lists are ordered relative to each other:

out = [{**i, **j} for i, j in zip(lst1, lst2)]

# Result

[{'cpu': '20.0', 'mem': '20.0', 'name': 'p1', 'pid': 814},
 {'cpu': '20.0', 'mem': '20.0', 'name': 'p2', 'pid': 999},
 {'cpu': '20.0', 'mem': '20.0', 'name': 'p3', 'pid': 1006},
 {'cpu': '20.0', 'mem': '20.0', 'name': 'p4', 'pid': 1152}]

Matches output:

In [292]: out == lst3
Out[292]: True

If the lists are not guaranteed to be sorted, you can sort on the common key, in this case name, before applying my method:

lst1, lst2 = (sorted(i, key=lambda x: x['name']) for i in [lst1, lst2])

Personally, I think your current method works fine, and it is very clear what you are doing. Also, my method of merging exclusively works in Python 3.5+

Sign up to request clarification or add additional context in comments.

Comments

0
l1 = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test1'}]
l2 = [{'id': 3, 'age': 10},{'id': 4, 'age': 10},{'id': 1, 'age': 10}, {'id': 2, 'age': 20}]


def m1(l1,l2):
    d = defaultdict(dict)
    for l in (l1,l2):
        for d1 in l :
            d[d1['id']].update(d1)
    aa = sorted(d.values(),key = itemgetter('id'))
    aap = print(aa)
    return aap        
            
m1(l1,l2)            
                        
"""
output :
[{'id': 1, 'name': 'test', 'age': 10}, {'id': 2, 'name': 'test1', 'age': 20}, {'id': 3, 'age': 10}, {'id': 4, 'age': 10}]
"""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.