-2
def enrollments(db : {str:{(str,str)}}) -> [(str,int)]:
    for node, value in db.items():
        lst=[] 
        lst.append((node, len(value)))
    print(lst)

The function tries to read a dictionary and return a two tuple list that contains the name of the key and the number of the values within the key. But when I run it, it shows:

enrollments({'ICS-31': {('Bob', 'A'), ('David', 'C'), ('Carol', 'B')}, 
             'Math-3A': {('Bob', 'B'), ('Alice', 'A')}
            })

[('Math-3A', 2)]

Were have I gone wrong?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
f0rex
  • 11
  • 1
  • 5
  • `lst` need to be defined before the `for` loop. – dkato Jan 14 '18 at 01:21
  • So it should be [('ICS-31',3),('Math-3A', 2)], but there is only one element in the list – f0rex Jan 14 '18 at 01:21
  • Failing to see the duplicate here. This is a question about reassigning a variable inside a loop. The alleged duplicate is about forgetting "return" when calling recursively. That doesn't seem like the same question to me. – Silvio Mayolo Jan 14 '18 at 01:22
  • 1
    @SilvioMayolo Whoops, misread the question. My bad. Happens every now and then. Although there is a dupe for this too :) – cs95 Jan 14 '18 at 01:35

2 Answers2

4

You are reassigning the lst variable to an empty list every iteration. Assign it once, before the loop:

lst = [] 
for node, value in db.items():
    lst.append((node, len(value)))

You can also use a comprehension and avoid the issue altogether:

lst = [(node, len(value)) for node, value in db.items()] 

The issue of returning None will be resolved by actually returning something:

def enrollments(db : {str:{(str,str)}}) -> [(str,int)]:
    return [(node, len(value)) for node, value in db.items()] 
user2390182
  • 72,016
  • 6
  • 67
  • 89
1
  • You actually don't even need to use .items(), you can simply do the following:

    def enrollments(dictionary):
        _return_list_ = []
        for node in dictionary:
            _return_list_.append((node,len(dictionary[node])))
        return _return_list_
    
itsmrbeltre
  • 412
  • 7
  • 18