我正在尝试在Python 3.7中编写一个类ResourcesBuilder
:
- 获取一些JSON数据:
-
accounts
:词典和父子帐户列表 -
service
:一些字符串标识符 -
data
:可以是字典,列表或字符串
-
- 使用输入数据动态构建嵌套字典,并将其返回为JSON
import json
class ResourcesBuilder:
def __init__(self):
self.parent_account = {}
self.accounts = {}
def build(self,parent_account,child_account,service,data):
self.parent_account[child_account] = {service: data}
self.accounts[parent_account] = self.parent_account
def main():
accounts = json.loads('{"p_acc_1": ["c_acc_1a","c_acc_1b"],"p_acc_2": ["c_acc_2a","c_acc_2b"]}')
service = 'test_service'
builder = ResourcesBuilder()
for parent_account in accounts:
for a_account in accounts[parent_account]:
data = 'test_data'
builder.build(parent_account,a_account,data)
print(json.dumps(builder.accounts,indent=4,sort_keys=True))
if __name__ == "__main__":
main()
运行时,以上代码当前返回:
## CURRENT OUTCOME
{
"p_acc_1": {
"c_acc_1a": {
"test_service": "test_data"
},"c_acc_1b": {
"test_service": "test_data"
},"c_acc_2a": {
"test_service": "test_data" <--- this should not be returned
},"c_acc_2b": {
"test_service": "test_data" <--- this should not be returned
}
},"p_acc_2": {
"c_acc_1a": {
"test_service": "test_data" <--- this should not be returned
},"c_acc_1b": {
"test_service": "test_data" <--- this should not be returned
},"c_acc_2a": {
"test_service": "test_data"
},"c_acc_2b": {
"test_service": "test_data"
}
}
}
如您所见,它列出了所有父帐户下的所有子帐户,而不是仅仅在其各自帐户下列出子帐户:
# DESIRED OUTCOME
{
"p_acc_1": {
"c_acc_1a": {
"test_service": "test_data"
},"c_acc_1b": {
"test_service": "test_data"
}
},"p_acc_2": {
"c_acc_2a": {
"test_service": "test_data"
},"c_acc_2b": {
"test_service": "test_data"
}
}
}
我从python开始,所以我将非常感激如何更好地实现自己的目标。
感谢您抽出宝贵的时间对此进行研究!
谢谢你, 乔治·M。