Python 创建两个词典的并集
我试图实现的是创建两个字典的并集(由单个整数组成,即1、2、3、4等),方法是从字典中取出键,将它们放入两个列表中,将两个列表合并,然后将它们放回包含两个列表的新字典中。然而,我遇到了麻烦Python 创建两个词典的并集,python,dictionary,Python,Dictionary,我试图实现的是创建两个字典的并集(由单个整数组成,即1、2、3、4等),方法是从字典中取出键,将它们放入两个列表中,将两个列表合并,然后将它们放回包含两个列表的新字典中。然而,我遇到了麻烦 TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'builtin_function_or_method' 我怎样才能避免这个错误呢 下面是相关的代码片段 class DictSet:
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])
您必须调用
keys()
方法。试试这个:
a = self.newDict.keys()
b = otherset.newDict.keys()
编辑:我看到你正在使用Python3。在这种情况下:
a = list(self.newDict)
b = list(otherset.newDict)
您必须调用
keys()
方法。试试这个:
a = self.newDict.keys()
b = otherset.newDict.keys()
编辑:我看到你正在使用Python3。在这种情况下:
a = list(self.newDict)
b = list(otherset.newDict)
为什么不使用
dict.update()
为什么不使用
dict.update()
今后,请在您的问题中包含完整的程序。它不需要很长(事实上,越短越好!),但它必须是完整的。有关如何通过提出此类问题获得优秀答案的说明,请参阅,尤其是。今后,请在问题中加入完整的程序。它不需要很长(事实上,越短越好!),但它必须是完整的。有关如何提出此类问题以获得出色答案的解释,请参阅,特别是。我做了您建议的更改,收到了不同的错误:TypeError:不支持的+操作数类型:'dict_keys'和'dict_keys'我做了您建议的更改,收到了不同的错误:TypeError:不支持的操作数类型对于+:“dict_键”和“dict_键”