user2916886
user2916886

Reputation: 845

forming a list of dictionary from a list in python

I have a list in python whose sample data looks like this:

list_str = ['1. Option 1', '2. Option 2 ', '3. Option 3', '4. Option 4']

Now what I want to do is form a list of dictionary using items from this list. The output list of dictionary should look like this:

[
                        {
                            "text": "1. Option 1",
                            "value": "1"
                        },
                        {
                            "text": "2. Option 2",
                            "value": "2"
                        },
                        {
                            "text": "3. Option 3",
                            "value": "3"
                        },
                        {
                            "text": "4. Option 4",
                            "value": "4"
                        }

                    ]

Now I tried this as first step to form the list of dictionary:

list_of_dict = dict((x,y) for x,y in enumerate(list_str,1))

which produces this output, which is not the correct output but I am unable to modify it further to get the desired output:

{1: '1. Option 1 ', 2: '2. Option 2 ', 3: '3. Option 3 ', 4: 'Option 4 '}

How can I modify my code to get the correct desired output?

Upvotes: 0

Views: 91

Answers (3)

Rahul K P
Rahul K P

Reputation: 16081

You can try like this,

In [11]: [{'value':str(x),'text':y} for x,y in enumerate(list_str,1)]
Out[11]: 
[{'text': '1. Option 1', 'value': '1'},
 {'text': '2. Option 2 ', 'value': '2'},
 {'text': '3. Option 3', 'value': '3'},
 {'text': '4. Option 4', 'value': '4'}]

List comprehension will be the solution, But you have to specify the key and value in each iteration, then only it will assign properly.

Upvotes: 0

AGN Gazer
AGN Gazer

Reputation: 8378

I would do like this (one of many possibilities):

list_of_dict = [{'text': s, 'value': s.split('.')[0]} for s in list_str] 

Upvotes: 0

Zizouz212
Zizouz212

Reputation: 4998

You can try:

dictionaries = []

for x, y in enumerate(list_str, 1):
    dictionaries.append({'text': y, 
                         'value': str(x)
                        })

Or make it a one liner:

dictionaries = [{'text': y, 'value': str(x)} for x, y in enumerate(list_str, 1)]

Upvotes: 2

Related Questions