-1

I have two list of dicts:

first_list = [{
                "symbol": "BTC",
                "price": 22809
               },
              {
                "symbol": "ETH",
                "price": 1626
              }
             ]

second_list = [{
                "symbol": "BTC",
                "volume": 22809333
               },
              {
                "symbol": "ETH",
                "volume": 19809333
              }
             ]


What is the best solution (without for or another bad time complexibility solutions) to merge two lists like:

final_list = [{
                "symbol": "BTC",
                "price": 22809,
                "volume": 22809333
               },
              {
                "symbol": "ETH",
                "price": 1626,
                "volume": 19809333
              }
             ]

1 Answers1

0
from itertools import zip_longest

out = [{**u, **v} for u, v in zip_longest(first_list, second_list, fillvalue={})]

#print(out)
[{'symbol': 'BTC', 'price': 22809, 'volume': 22809333},
 {'symbol': 'ETH', 'price': 1626, 'volume': 19809333}]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • Thank you for your answer! The community would appreciate if in addition to code you can provide a description / extensive comments to improve it. For example, I think it is a great opportunity to explain (or point to relevant documentation) how `zip_longest` works or what `{**u, **v}` does. – mingaleg Feb 06 '23 at 21:19
  • 1
    The important thing about using the zip_longest method is that the items in the lists must be sorted and similar items must be compressed together. Unless your data is wrong and you are not aware of it. – Pourya Mansouri Feb 07 '23 at 09:11
  • 1
    The best thing to do is to sort both lists based on a specific element and check when combining – Pourya Mansouri Feb 07 '23 at 09:13
  • 1
    first_list = sorted(first_list, key=lambda x: x.get('symbol')) second_list = sorted(second_list, key=lambda x: x.get('symbol')) final_list = [u | v for u, v in zip_longest(first_list, second_list, fillvalue={}) if u.get('symbol') == v.get('symbol')] – Pourya Mansouri Feb 07 '23 at 09:15