Issue
I have a list which looks like this:
lst = ['a', 'b', 'c']
I want to iterate through that list to get a dictionary like:
dict = {'jobs': [{'id':'a'}], [{'id':'b'}], [{'id':'c'}]}
I tried looping through the elements of the list, like:
lst = ['a', 'b', 'c']
dict = {'jobs':[{}]}
for key in range(len(lst)):
dict['jobs'][key]['id'] = list[key]
print(dict)
But I get an out of range error.
Any suggestions?
Solution
You can use:
lst = ['a', 'b', 'c']
{'jobs' : [{'id' : x} for x in lst]}
# {'jobs': [{'id': 'a'}, {'id': 'b'}, {'id': 'c'}]}
Answered By - Jonas Palačionis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.