1

I can't get the return value from find_total() function in DictionaryTest class, when I iterate over channel_list dictionary. Python interpreter gives me this error:

TypeError: 'int' object is not iterable

What did I do wrong in the code?

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())
MSeifert
  • 145,886
  • 38
  • 333
  • 352
yasmikash
  • 157
  • 2
  • 14

2 Answers2

1

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())
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

You should iterate dictionary's 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())
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
errata
  • 5,695
  • 10
  • 54
  • 99