Skip to content
Advertisement

Transform list to dictionary with ID’s and content [closed]

Given list is llist = ['4|right', ' 2|left', ' 2|down', ' 2|right']

And the output must be like this:

outp = [
    {'id': 0, 'content': '4|right'},
    {'id': 1, 'content': '2|left'},
    {'id': 2, 'content': '2|down'},
    {'id': 3, 'content': '2|right'}
]

Advertisement

Answer

The provided output is invalid (a set cannot hold dictionaries as those are not hashable), assuming you want a list of dictionaries:

outp = [{'id': i, 'content': s.strip()} for i, s in enumerate(llist)]

output:

[{'id': 0, 'content': '4|right'},
 {'id': 1, 'content': '2|left'},
 {'id': 2, 'content': '2|down'},
 {'id': 3, 'content': '2|right'}]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement