【发布时间】:2021-09-21 19:01:37
【问题描述】:
我目前正在为我用 Python 编写的一段特定代码而苦苦挣扎。
我需要根据同一个键获取单独对象值的总值。
这是我目前得到的 JSON 数据
[{
"name": "John",
"data": [{
"currency": "Euro",
"amount": 100.00
},
{
"currency": "Dollar",
"amount": 223
},
{
"currency": "Yen",
"amount": 800
}
]
},
{
"name": "Jack",
"data": [{
"currency": "Dollar",
"amount": 32
},
{
"currency": "Euro",
"amount": 80
}
]
},
{
"name": "Elise",
"data": [{
"currency": "Dollar",
"amount": 12
},
{
"currency": "Yen",
"amount": 66
}
]
}
]
但是!在这个对象数组中,我还想添加另一个对象,其中包含有关每种货币总值的信息。我一直在为此苦苦挣扎,我尝试过嵌套 for 循环,但感觉这是浪费时间,必须有更快的方法......
谁能帮我得到我正在寻找的输出?
想要的输出 =
[{
"name": "Total",
"data": [{
"Euro": {
"amount": 180
},
"Dollar": {
"amount": 267
},
"Yen": {
"amount": 866
}
}]
},
{
"name": "John",
"data": [{
"currency": "Euro",
"amount": 100.00
},
{
"currency": "Dollar",
"amount": 223
},
{
"currency": "Yen",
"amount": 800
}
]
},
{
"name": "Jack",
"data": [{
"currency": "Dollar",
"amount": 32
},
{
"currency": "Euro",
"amount": 80
}
]
},
{
"name": "Elise",
"data": [{
"currency": "Dollar",
"amount": 12
},
{
"currency": "Yen",
"amount": 66
}
]
}
]
【问题讨论】:
-
您的每个人的
data有时有currency,有时有asset_id。有没有一致性?它们会被解释为同一个东西吗? -
嘿!对不起,这是一个错误,都是货币!
-
欢迎来到 Stack Overflow!请拨打tour,阅读what's on-topic here、How to Ask和question checklist,并提供minimal reproducible example。 “为我实现此功能”与此站点无关。你必须诚实地尝试,然后就你的算法或技术提出一个具体问题。
-
你好@PranavHosangadi。我已经尝试了几个小时来获取这段代码,但没有成功,很抱歉,但我无法为“Total”部分提供一段工作代码。
-
为什么没有成功? debugging你做了什么?你得到什么错误?您要求我们为您提供代码来完成您的工作,但您自己没有表现出任何努力。您需要展示您的代码并询问您在代码中遇到的特定问题。堆栈溢出不是免费的在线编码服务。您了解如何迭代列表的元素吗?如何访问字典中的项目?如何将数字添加到字典的特定键?您具体遇到了什么问题?
标签: python arrays json algorithm object