gpt4 book ai didi

Python字典: function to populate dictionary overwriting earlier call of the same function

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:57 25 4
gpt4 key购买 nike

我正在尝试构建一个数据结构,在字典中组织某些人口统计数据,其中初始键是区域(美洲、欧洲等)。每个的值都是一个字典,其中包含键:值国家/地区代码:数据值。我为实现此目的而编写的函数似乎可以工作,但是在同一脚本中第二次调用并分配不同的变量名称时,它不仅返回该调用的预期字典,而且覆盖第一次调用中生成的字典。

我尝试在调用函数 (dictionaryName = functionCall()) 之前为变量创建一个空字典 (dictionaryName = {})。我还尝试制作函数参数所需的字典的副本,并传入副本而不是原始副本,并从函数返回副本而不是带有我用作的空白值的字典的修改版本模板。在所有情况下,第二个函数调用仍然会覆盖在第一个函数中创建的变量。

这些是函数调用:

orderedData1960 = insertDataIntoCategoryAndCodesDictionary(data1960, dictionaryOfRegionsAndCodes)
orderedData2013 = insertDataIntoCategoryAndCodesDictionary(data2013, dictionaryOfRegionsAndCodes)

这是函数本身:

def insertDataIntoCategoryAndCodesDictionary(dataSet, categoriesAndCodesDictionary):
for category in categoriesAndCodesDictionary:
updateData(categoriesAndCodesDictionary[category], dataSet)
return categoriesAndCodesDictionary

def updateData(category, dataSet):
for key in category:
category.update({key: dataSet.get(key)})

orderedData1960orderedData2013 最终应成为同一结构中的 2 个不同数据集;目前的实际结果是它们最终是相同的。

最佳答案

编辑:我误解了一些东西。问题是您的第一个函数返回第二个参数,因为您没有在函数中的任何位置覆盖它。

关于Python字典: function to populate dictionary overwriting earlier call of the same function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com