-2

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'}]
            
Kumar
  • 29
  • 1
  • 6
  • 1
    It's not possible to have several identical keys in a dict. – Corralien Feb 13 '23 at 19:43
  • @Corralien While technically true, it is none the less possible to construct a simple object that would effectively allow for multiple semi-duplicate keys. I'm guessing you know that, but just noting it here for other future visitors. Of course, if we did such a thing it would be of highly dubious value. – JonSG Feb 13 '23 at 20:08
  • @Kumar Are you sure that is the result you seek? It would be very uncommon to want such a result. Any chance you want more like `{"Parent Name": ["value 1", "value 2", "value 3"]}` or perhaps `{"Parent Name": [("name", "value 1"), ("name", "value 2"), ("name", "value 3")]}`? – JonSG Feb 13 '23 at 20:18
  • @jonSG, the data i get from my command has same multiple keys but different values, how to achieve {"Parent Name": ["value 1", "value 2", "value 3"]}?? – Kumar Feb 13 '23 at 20:20
  • Try: `{"Parent Name" : [x["Name"] for x in data_1]}` – JonSG Feb 13 '23 at 20:22

1 Answers1

0
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"]}
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • it is *technically* possible to get that output if we allow object instances to be keys. – JonSG Feb 13 '23 at 20:34