nested dict in a list with custom string

Question:

Below is my list, how can i add a string called "Parent Name" so that all "Name" and their "values" are nested under "Parent name" like below

data_1 = [{'Name': 'value 1'},
{'Name': 'value 2'},
{'Name': 'value 3'}]

how to get below:

 [{'Parent Name':{ 'Name': 'value 1', 'Name': 'value 2', 'Name': 'value 3'}]
            
Asked By: Kumar

||

Answers:

data_1 = [{'Name': 'value 1'},
{'Name': 'value 2'},
{'Name': 'value 3'}]

In your question you said you need output like:

[{'Parent Name':{ 'Name': 'value 1', 'Name': 'value 2', 'Name': 'value 3'}]

However, you cannot get this exact output as 'Name' will override with the latest value.

If you run :

{ 'Name': 'value 1', 'Name': 'value 2', 'Name': 'value 3'}

you will get:

{'Name': 'value 3'}

In the comments, you are saying you need :

{"Parent Name": ["value 1", "value 2", "value 3"]}

you can get this by (as @JonSG commented)

{"Parent Name" : [x['Name'] for x in data_1]}

#output
{"Parent Name": ["value 1", "value 2", "value 3"]}
Answered By: God Is One
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.