python - 类中的嵌套字典

标签 python dictionary

<分区>

我遇到此数据结构的意外行为。

    class IncomeVerification(object):

        data = {'IncomeYears': []}

        def __init__(self, income_years):
            for year in income_years:
                new_year = IncomeYear(year).data
                self.data['IncomeYears'].append(new_year)

    class IncomeYear(object):
        data = {'IncomeYear': {'Year': None}}

        def __init__(self, year, reported_income=None):
            self.data['IncomeYear']['Year'] = year

    income_years = ['2014', '2013', '2012', '2011']

    foo = IncomeVerification(income_years)
    print foo.data

返回,

     {'IncomeYears': [{'IncomeYear': {'Year': '2011'}}, {'IncomeYear': {'Year': '2011'}}, {'IncomeYear': {'Year': '2011'}}, {'IncomeYear': {'Year': '2011'}}]}

我很期待,

    {'IncomeYears': [{'IncomeYear': {'Year': '2014'}}, {'IncomeYear': {'Year': '2013'}}, {'IncomeYear': {'Year': '2012'}}, {'IncomeYear': {'Year': '2011'}}]}

我相信我的词典的嵌套性质会产生独特的关键问题,因此会覆盖现有条目。关于如何修改上述调用以获得我想要的结果的任何想法?

谢谢。

最佳答案

您在自己的代码中使用 self.data['IncomeYears'].append(new_year) 重复添加引用而不是新的 dict/object,所以任何时候您进行更改实际上是在更改同一个对象。

您需要使用自己的代码深度复制数据:

from copy import deepcopy
class IncomeVerification(object):

        data = {'IncomeYears': []}
        def __init__(self, income_years):
            for year in income_years:
                new_year = deepcopy(IncomeYear(year).data)

哪个会输出:

{'IncomeYears': [{'IncomeYear': {'Year': '2014'}}, {'IncomeYear': {'Year': '2013'}}, {'IncomeYear': {'Year': '2012'}}, {'IncomeYear': {'Year': '2011'}}]}

或者更好的做法是让 data 成为 IncomeYear 中的 instance attribute 而不是当前创建一次并共享的类属性在所有实例中:

class IncomeVerification(object):
        data = {'IncomeYears': []}
        def __init__(self, income_years):
            for year in income_years:
                new_year = IncomeYear(year).data
                self.data['IncomeYears'].append(new_year)

class IncomeYear(object):
    def __init__(self, year, reported_income=None):
        # new dict/object for each instance
        self.data = {'IncomeYear': {'Year': None}}
        self.data['IncomeYear']['Year'] = year

income_years = ['2014', '2013', '2012', '2011']

foo = IncomeVerification(income_years)
print(foo.data)

再次输出:

{'IncomeYears': [{'IncomeYear': {'Year': '2014'}}, {'IncomeYear': {'Year': '2013'}}, {'IncomeYear': {'Year': '2012'}}, {'IncomeYear': {'Year': '2011'}}]}

class vs instance attributes

关于python - 类中的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33267299/

相关文章:

python - “x”是此函数的无效关键字参数

python - 如何在 Python 中将 dict 元素值作为列表

javascript - 如何从字典中填充大型数据列表(~2000 项)

Python如何在其中也包含字符串的列表中获取数字总和

Python Apscheduler 条件任务

python - 接下来 n 行的更复杂的滚动总和

安装 EB CLI 3.0 后出现 Python DistributionNotFound 错误

python - 更新字典对象中的值

python - 从集合模块重新发明 Counter 类

javascript - 我如何从不返回简单 HTML 的网站上抓取数据