I have the following dictionary:
{'expert_interests': "['Machine learning', 'deep learning']"}
As you can see the the value of the key "expert_interests" is the String "[‘Machine learning’, ‘deep learning’]".
I want to convert this string value into a nested dictionary such that the dictionary looks like this:
{'expert_interests': [
{
"title": "Machine learning"
},
{
"title": "deep learning"
}
]
}
I do not know how to approach this problem.Any help is highly appreciated
2
Answers
You can use
ast.literal_eval
to convert the value to a list of strings and use a list comprehension to create a list of dicts from it.The best option is to use
ast.literal_eval
. This function is likeeval
, except it will only evaluate literals, so it’s safer from attacks.From the documentation (linked above),
Another option is to use
json.loads
to convert it to a list of strings, then just make each a dictionary.The only problems with this are that it blindly replaces
'
with"
(since the JSON standard only uses"
for strings) which can lead to errors if you have"
or'
anywhere in your string, but this is better thaneval
becauseeval
is dangerous especially when you can’t trust the source.