2016-04-14 87 views
0

我试图完成的是通过从字典中取出键来创建两个词典的联合(包括单个整数,即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]) 
+0

未来,请在您的问题中包含一个完整的程序。它不必很长(实际上,越短越好!),但它必须完整。有关如何询问这些问题如何产生出色答案的解释,请参见[问],尤其是[mcve]。 –

回答

2

您必须致电keys()方法。试试这个:

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

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

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

我做了您提出的更改并收到了一个不同的错误:TypeError:不支持的操作数类型为+:'dict_keys'和'dict_keys' – corbrrrrr

2

为什么不使用dict.update()

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