Python词典:用于填充字典覆盖相同功能的早期调用的函数

问题描述 投票:1回答:1

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

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

这些是函数调用:

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
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.