Porjaz
Porjaz

Reputation: 791

Python create dictionary from a list that has key:value strings

I have a list second_list that contains the following data:

 {"forename":"SomeForename","surname":"SomeSurname","title":"MR"}
 {"postTown":"LONDON"}
 {"country":"ZIMBABWE"}
 {"forename":"SomeOtherForename","surname":"SomeOtherSurname"}
 {"postTown":"LONDON"}
 {"country":"ZIMBABWE"}

and I am trying to convert that list to a dictionary like this:

dict_values = {}
for i in second_list:
    dict_values.update(ast.literal_eval(i))

but the key and value of the dictionary get overwritten with the last key and value. So, I get a dictionary with the following data:

{"forename":"SomeOtherForename","surname":"SomeOtherSurname"}
{"postTown":"LONDON"}
{"country":"ZIMBABWE"}

What I would like to achieve is to have dictionary with list as a value like this:

{'forename':[someForename, SomeOtherForename], 'surname:'[someSurname, someOtherSurname]}

etc.

Is there a way to convert all the data from list to a dictionary without overwriting it?

Upvotes: 0

Views: 57

Answers (1)

Tiago
Tiago

Reputation: 9557

from collections import defaultdict
dict_values = defaultdict(list)
for i in second_list:
    for k, v in ast.literal_eval(i).iteritems():
        dict_values[k].append(v)

Upvotes: 2

Related Questions