0

I have a large list of dictionaries, each with exactly one entry and with unique keys, and I want to 'combine' them into a single dict with python 3.8.

So here is an example that actually works:

mylist = [{'a':1}, {'b':2}, {'c':3}]
mydict = {list(x.keys())[0]:list(x.values())[0] for x in mylist}

which gives as result the expected output:

 {'a': 1, 'b': 2, 'c': 3}

But it looks ugly and not quite pythonic. Is there a better one-line solution to this problem?

This is similar to the question asked HERE, but in my example I am looking for an answer (1) to merge many dicts together and (2) for a one-line solution. That makes my question different from the question already asked.

Alex
  • 41,580
  • 88
  • 260
  • 469

2 Answers2

1
mydict = { k:v for elt in mylist for k, v in elt.items()}
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
0

Try this out, simple and effective.

mylist = [{'a':1}, {'b':2}, {'c':3}]
result = {}
for d in mylist:
    result.update(d)

Result

{'a': 1, 'b': 2, 'c': 3} 
tlc_44
  • 9
  • 2