Home > Software engineering >  How to create a dictionary assigning values from a list and generate the same key for each one
How to create a dictionary assigning values from a list and generate the same key for each one

Time:11-21

I have a list and I'd like that each item of the list becomes the value of a key that doesn't exist yet but should be created.

This is the list:

['King', 'President', 'VP', ' 2nd VP', '3rd VP']

The desired output must be like this:

[{'title':'King'}, {'title':'President'}, {'title':'VP'}, {'title':'2nd VP'}, {'title':'3rd VP'}]

Thanks for your support

CodePudding user response:

You can do so with list comprehension

titles = ['King', 'President', 'VP', ' 2nd VP', '3rd VP']

print([{'title': title} for title in titles])

# output
[{'title': 'King'}, {'title': 'President'}, {'title': 'VP'}, {'title': ' 2nd VP'}, {'title': '3rd VP'}]

CodePudding user response:

You can do that using List Comprehension

lst = ['King', 'President', 'VP', ' 2nd VP', '3rd VP']
d_lst = [{'title': v} for v in lst]
d_lst = [{'title': 'King'}, {'title': 'President'}, {'title': 'VP'}, {'title': ' 2nd VP'}, {'title': '3rd VP'}]

CodePudding user response:

Like this?:

liste = ['King', 'President', 'VP', ' 2nd VP', '3rd VP']

for i in range(0, 5):
    liste[i] = {'title':liste[i]}
  • Related