首页 > 解决方案 > 将新字典项添加到嵌套字典

问题描述

cities={

    'city1':{

         'name':'sydney',

         'country':'australia',

         'desc':'beautiful'

},
 
   'city2':{

        'name':'toronto',

        'country':'canada',

        'desc':'amazing',

    }

}

cities['city3']:"{'name':'Tokyo','country':'japan','desc':'lots of earthquakes’}"

for keys,values in cities.items():
    print(f"{keys}--->{values}”)

这是我的代码。到目前为止,我是 python 和学习词典的新手。我正在尝试将字典添加到现有字典中,但它不起作用。我没有错误,仍然只获得前两个城市的信息。我认为我的语法一定是错误的。谁能帮我解决这个问题>?

输出:

在此处输入图像描述

标签: pythondictionary

解决方案


尝试将您的插入代码更改为:

cities['city3'] = {'name':'Tokyo','country':'japan','desc':'lots of earthquakes'}

您可能不想将其添加为字符串,因此请不要使用引号。此外,在描述的末尾有一个错误的引号。


推荐阅读