【问题标题】:Creating a union of two dictionaries创建两个字典的并集
【发布时间】:2016-08-06 18:02:14
【问题描述】:

我试图完成的是创建两个字典的联合(由单个整数组成,即 1、2、3、4 等),方法是从字典中取出键,将它们放入两个列表中,加入这两个列表,然后将它们放回包含两个列表的新字典中。但是,我遇到了

TypeError: unsupported operand type(s) for +: 
    'builtin_function_or_method' and 'builtin_function_or_method'

我该如何解决这个错误?

这里是相关的代码。

class DictSet:
    def __init__(self, elements):
        self.newDict = {}
        for i in elements:
            self.newDict[i] = True

    def union(self, otherset):
        a = self.newDict.keys
        b = otherset.newDict.keys
        list1 = a + b
        new = DictSet(list1)
        return new

def main():
    allints = DictSet([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    odds = DictSet([1, 3, 5, 7, 9])
    evens = DictSet([2, 4, 6, 8, 10])

【问题讨论】:

  • 以后,请在您的问题中包含一个完整的程序。它不必很长(事实上,越短越好!)但它必须是完整的。有关提出此类问题如何获得出色答案的说明,请参阅How to Ask,尤其是minimal reproducible example

标签: python dictionary


【解决方案1】:

为什么不使用dict.update()

def union(self, otherset):
    res = DictSet([])
    res.newDict = dict(self.newDict)
    res.newDict.update(otherset.newDict)
    return res

【讨论】:

    【解决方案2】:

    您必须调用keys() 方法。试试这个:

        a = self.newDict.keys()
        b = otherset.newDict.keys()
    

    编辑:我看到你正在使用 Python3。在这种情况下:

        a = list(self.newDict)
        b = list(otherset.newDict)
    

    【讨论】:

    • 我进行了您建议的更改并收到了另一个错误:TypeError: unsupported operand type(s) for +: 'dict_keys' and 'dict_keys'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多