Iterate over a dictionary using 'for' loop in a class
This question already has an answer here:
It seems you want to iterate over keys and values . You can accomplish this by iterating over the items() :
for channel_num, channel_det in self.dictionary.items():
In your case for something in self.dictionary: iterates only over the keys. And the keys are integers. But you try to unpack the integer into two values: channel_num, channel_det which is why it failed.
Additional comments:
You only need the values in your for -loop so you could also iterate over the values() only:
for channel_det in self.dictionary.values():
And the really advanced method would be to use a generator expression and the built-in sum function:
def find_total(self):
return sum(channel_det['charge'] for channel_det in self.dictionary.values())
你应该迭代字典的items :
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())
链接地址: http://www.djcxy.com/p/30370.html
上一篇: 如何从字典中获得价值..?
下一篇: 在类中使用'for'循环迭代字典
