1

In python3 I have 2 lists:

listA = [{'aString': 'someone', 'aNumber': 123}]
listB = [{'anotherNumber': 456}]

How do I combine them into 1 single list which looks like this?

listC = [{'aString': 'someone', 'aNumber': 123, 'anotherNumber': 456}]

If I use,

listC = listA + listB

I get:

listC = [{'aString': 'someone', 'aNumber': 123}, {'anotherNumber': 456}]
stovfl
  • 14,998
  • 7
  • 24
  • 51
Joe
  • 380
  • 3
  • 17
  • 2
    Possible duplicate of [How to merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression) – Chris Feb 26 '19 at 13:14
  • you don't actually look for merging lists but merging dictionaries in lists. you can merge dictionaries with dict.update(). – Tryph Feb 26 '19 at 13:15
  • you have two list of dicts – Brown Bear Feb 26 '19 at 13:15

2 Answers2

3

You can unpack the two lists into the dict constructor and then unpack the two dicts into one:

[{**dict(*listA), **dict(*listB)}]
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Try using :

listC = dict(listA .items() + listB.items())
Smaiil
  • 139
  • 1
  • 5
  • his answer came in Low Quality posts in SO since its code only answer.... Could you add any commentary to your answer? Explain your logic, and give a little commentary on what your code is intended to do. This will help the OP, but it will also serve as commentary for future users – Ram Ghadiyaram Feb 26 '19 at 20:00