如何在不更新python中的键值的情况下遍历字典

时间:2020-03-21 06:40:57

标签: python dictionary

我正面临这种情况:我有一本具有以下架构的字典:

data = {
  "country": "",
  "lat": "",
  "long": ""
}

我想通过遍历我拥有的国家/地区列表并将其附加到列表中来填充该列表。 预期结果是:

countriesData = [
   {
      "country": "country1",
       ...
   },
   {
      "country": "country2",
       ...
   }
]

我运行下一个脚本,但我得到的只是字典列表,在“ country”键中具有重复的值: 脚本

for country in countries:
    dict["country"] = country
    countriesData.append(dict)

输出

[
   {
      "country": "country1",
       ...
   },
   {
      "country": "country1",
       ...
   },
   { 
      "country": "country1"
   }
]

我是python的新手,如果您能帮助我,我将不胜感激。 问候

2 个答案:

答案 0 :(得分:0)

for item in data:
    toadd["country"] = item["country"]
    countriesData.append(toadd)

扩展评论-您将相同的内容添加到新列表中。

答案 1 :(得分:0)

很难用省略号准确地告诉您您想在这里做什么。似乎您想让countriesData的对象符合顶部的架构,但是您的示例代码仅处理"country"键。

无论如何,一种更Python-y的方式来执行我认为想要的操作将是使用理解力,例如:

countriesData = [{"country": country} for country in countries]

这与以下内容基本相同:

countriesData = []
for country in countries:
    countriesData.append({"country": country})