英文:
nested dict in a list with custom string
问题
以下是我的清单,如何添加一个名为“Parent Name”的字符串,以便所有的“Name”及其“values”都嵌套在“Parent Name”下,如下所示:
data_1 = [{'Name': 'value 1'},
{'Name': 'value 2'},
{'Name': 'value 3'}]
如何获得以下结果:
[{'Parent Name': {'Name': 'value 1', 'Name': 'value 2', 'Name': 'value 3'}}]
英文:
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'}]
答案1
得分: 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"]}
英文:
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"]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论