0

I would apply the following code for list of dictionaries :

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}

z = {**x, **y}     # get z= {'a': 1, 'b': 3, 'c': 4} (without duplicated keys)

I create a list (List_Dict) of several dictionaries stored like:

List_Dict[0] = {'a': 1, 'b': 2}
List_Dict[1]  = {'c': 3, 'a': 4}
List_Dict[2]  = {'b': 1, 'c': 2}
...    ...    ...    ...    ...
List_Dict[5000]  = {'d': 3, 'a': 4}

the list contains 5000 dictionaries

I ask if there is any simple method for typing between bracket the whole elements (5000) dynamically for applying this instruction:

z = {**List_Dict[0],**List_Dict[1],**List_Dict[2] ....,**List_Dict[5000]} 
  • Have you ever heard of pandas ? https://pandas.pydata.org/ – ma3oun Nov 26 '19 at 15:23
  • each dictionarry has a diffirent number of element I cant fix the number of column and each dictionarry has more than 100 key . so that I would like to apply this method – Diana_doudi Nov 26 '19 at 15:41
  • Possible duplicate of [Unpack list of dictionaries in Python](https://stackoverflow.com/questions/58940431/unpack-list-of-dictionaries-in-python) – Georgy Nov 26 '19 at 15:48
  • Also: [How do I merge a list of dicts into a single dict?](https://stackoverflow.com/questions/3494906/how-do-i-merge-a-list-of-dicts-into-a-single-dict) – Georgy Nov 26 '19 at 15:49

2 Answers2

1

The way to do this in O(n) time is to use the the dict.update method to collect all of the entries in a single dict.

result = dict()

for d in List_Dict:
    result.update(d)

Using update is better than the {**result, **d} syntax because that creates a new dictionary on every iteration; there are n iterations and the new dictionary's size is O(n), so that solution would take O(n^2) time.

kaya3
  • 47,440
  • 4
  • 68
  • 97
0

You can simply put it in a for loop:

z = {}
for d in List_Dict:
    z = {**z, **d}
print(z)
LeoE
  • 2,054
  • 1
  • 11
  • 29
  • This solution is unnecessarily O(n^2) since it creates O(n) dictionaries of average length O(n). – kaya3 Nov 26 '19 at 15:28