如何在python中动态追加字典的字典?

2024-10-06 11:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

以前我静态地初始化过。这很好用

dict = {
   
   'telco_recharge_non_wallet': {
   'robi_at' : telco_recharge_non_wallet['robi_at'],
   'tt' : telco_recharge_non_wallet['tt'],
   'bl' : telco_recharge_non_wallet['bl'],
   'gp' : telco_recharge_non_wallet['gp'],
   }  
}

我想要这个。(我试过了,但解决不了。)

for tel in telcos:
    dict['telco_recharge_non_wallet'] = {
         tel : telco_recharge_non_wallet[tel]
    }

问题是我无法附加dict of dict。我尝试的方法只是获取最后插入的值

  • 输入:print(dict['telco_recharge_non_wallet'])

  • 输出:

{'robi_at': [['xxx', Decimal('000')], ['xxx', Decimal('000')]]}
{'tt': [['xxx', Decimal('000')], ['xxx', Decimal('000')]]}
{'bl': [['xxx', Decimal('000')], ['xxx', Decimal('000')]]}
{'gp': [['xxx', Decimal('000')], ['xxx', Decimal('000')]]}

Tags: for静态dictatxxxwalletgpdecimal
2条回答

试试这个:

intermediate_dict = {}
for tel in telcos:
    intermediate_dict[tel] = telco_recharge_non_wallet[tel]

final_dict = {'telco_recharge_non_wallet': intermediate_dict}

您的问题和代码存在一些问题

  1. 你不应该覆盖dict类
  2. 你的问题并不能真正解释你想做什么
  3. 您的代码格式不正确。(我知道,这不会改变Python中的任何内容,但很难阅读。)

提问前请先阅读how to ask

也许你在找这个:

data = {
   'telco_recharge_non_wallet': {
       'robi_at': telco_recharge_non_wallet['robi_at'],
       'tt': telco_recharge_non_wallet['tt'],
       'bl': telco_recharge_non_wallet['bl'],
       'gp': telco_recharge_non_wallet['gp'],
   }  
}

for tel in telcos:
    data['telco_recharge_non_wallet'][tel] = telco_recharge_non_wallet[tel]

相关问题 更多 >