2016-04-14 74 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