0

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?

1 Answer 1

2
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.