在一个包含自定义字符串的列表中的嵌套字典

huangapple go评论63阅读模式
英文:

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"]}

huangapple
  • 本文由 发表于 2023年2月14日 03:40:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定