Iterate over a dictionary using 'for' loop in a class
本问题已经有最佳答案,请猛点这里访问。
当我遍历
TypeError: 'int' object is not iterable
我在代码中做了什么错误?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class DictionaryTest: def __init__(self, dictionary): self.dictionary = dictionary def find_total(self): total = 0 for channel_num, channel_det in self.dictionary: total += channel_det['charge'] return total channel_list = {1: {'name': 'Sony PIX', 'charge': 3}, 2: {'name': 'Nat Geo Wild', 'charge': 6}, 3: {'name': 'Sony SET', 'charge': 3}, 4: {'name': 'HBO - Signature', 'charge': 25}} user_2 = DictionaryTest(channel_list) print(user_2.find_total()) |
似乎您想要迭代
1 | for channel_num, channel_det in self.dictionary.items(): |
在您的例子中,
您只需要
1 | for channel_det in self.dictionary.values(): |
真正先进的方法是使用生成器表达式和内置的
1 2 | def find_total(self): return sum(channel_det['charge'] for channel_det in self.dictionary.values()) |
您应该迭代字典的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class DictionaryTest: def __init__(self, dictionary): self.dictionary = dictionary def find_total(self): total = 0 for channel_num, channel_det in self.dictionary.items(): #Changed here only ^ total += channel_det['charge'] return total channel_list = {1:{'name': 'Sony PIX', 'charge':3}, 2:{'name': 'Nat Geo Wild', 'charge':6}, 3:{'name': 'Sony SET', 'charge':3}, 4:{'name': 'HBO - Signature', 'charge':25}} user_2 = DictionaryTest(channel_list) print(user_2.find_total()) |