EN VI

Python - why does py iterate dict keys fail to print keys?

2024-03-17 08:00:07
Python - why does py iterate dict keys fail to print keys?

I'm new to py and ran into an unexpected behavior :

tracker = Dict[int, List[int]]      
tracker.update({1: {1,2,3}})
tracker.update({2: {4,5,6}})
tracker.update({3: {7,8,9}})
for key in tracker:
  print(key)

stdout:

*typing.Dict[int, typing.List[int]]

I was expecting this output :

1
2
3

Can someone explain this behavior, and also describe how to iterate and print the dict keys ?

Solution:

You've assigned the Type Definition to tracker, not an actual instance of a dictionary.

Also {1,2,3} is a set, not a list.

tracker: Dict[int, List[int]] = dict()
    
tracker.update({1: [1,2,3]})
tracker.update({2: [4,5,6]})
tracker.update({3: [7,8,9]})

for key in tracker.keys():
  print(key)

Or...

tracker: Dict[int, List[int]] = dict()
    
tracker[1] = [1,2,3]
tracker[2] = [4,5,6]
tracker[3] = [7,8,9]

for key in tracker.keys():
  print(key)

Or...

tracker: Dict[int, List[int]] = {
   1: [1,2,3], 
   2: [4,5,6], 
   3: [7,8,9], 
}

for key in tracker.keys():
  print(key)
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login