3

I have a list like this

[[{1:"one",2:"two"},{1:"one"}],[{3:"three",4:"four"},{3:"three"}]]

required output:

[{1:"one",2:"two"},{1:"one"},{3:"three",4:"four"},{3:"three"}]

Can someone please tell me how to proceed?

zwer
  • 24,943
  • 3
  • 48
  • 66
Arohi Gupta
  • 95
  • 1
  • 8
  • This is called flattening a list. See https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python, https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python?noredirect=1&lq=1. A good answer is `[item for sublist in L for item in sublist]` – Stuart Jun 13 '17 at 22:27

2 Answers2

1

Iterate over the list's lists to add that to another list.

list_1 = [[{1:"one",2:"two"},{1:"one"}],[{3:"three",4:"four"},{3:"three"}]]
list_2 = []
for list in list_1:
    for dictionary in list:
        list_2.append(dictionary)

print(list_2)  # [{1: 'one', 2: 'two'}, {1: 'one'}, {3: 'three', 4: 'four'}, {3: 'three'}]
0

You can try this:

from itertools import chain

l = [[{1:"one",2:"two"},{1:"one"}],[{3:"three",4:"four"},{3:"three"}]]

new_l = list(chain(*l))

Final Output:

[{1: 'one', 2: 'two'}, {1: 'one'}, {3: 'three', 4: 'four'}, {3: 'three'}]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102