-1

I have a list like this:

list = [{'a': 1}, {'b': 2}, {'c': 3}]

i want to convert that list to dict like this:

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

anyone can help me ?

Fikran
  • 5
  • 3
  • 2
    please check it. it help you. https://stackoverflow.com/questions/3494906/how-do-i-merge-a-list-of-dicts-into-a-single-dict – Jignasha Royala Mar 06 '21 at 04:51
  • 2
    Does this answer your question? [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) – programandoconro Mar 06 '21 at 04:55
  • Those links already provided are helpful. And you also shouldn't use `list` and `dict` as variable names, otherwise your won't have access to those type names anymore. – Shihao Xu Mar 06 '21 at 05:48

3 Answers3

2
lst = [{'a': 1}, {'b': 2}, {'c': 3}]
result = {}

for elm in let:
    for i,value in elm.items():
        dictionary[i] = value

print(results)
1

Use a nested loop to flatten the list of dicts, then use the dict constructor.

l = [{'a': 1}, {'b': 2}, {'c': 3}]
result = dict(i for d in l for i in d.items())

It's also possible to "merge" these dicts into one in place:

l = [{'a': 1}, {'b': 2}, {'c': 3}]
result = l[0]
for d in l[1:]:
    result.update(d)
David Pi
  • 142
  • 1
  • 2
0

Create empty dictionary and using for loop you can add key : value to dictionary.

lst = [{'a': 1}, {'b': 2}, {'c': 3}]
my_dict = {}

for ele in lst:
    for k,v in ele.items():
        my_dict[k] = v

print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
Shihao Xu
  • 721
  • 1
  • 7
  • 14
Rima
  • 1,447
  • 1
  • 6
  • 12