Source code
x = {'a': 1, 'b': 2, 'd': 3, 'c' : 4}
d = list (x.keys ())
for key in sorted (d):
print (key + '= & gt;' + d [key])
Error
Traceback (most recent call last):
File "C: / Python projects / qq.py", line 4, in & lt; module & gt;
print (key + '= & gt;' + d [key])
TypeError: list indices must be integers or slices, not str
Reading Mark Lutz – Python, 5th Edition and ran into a little problem. I’m using python 3.6.
Answer 1, authority 100%
There is a suspicion that there should be x [key]
, not d [key]
, otherwise the code doesn’t make much sense.
Answer 2, authority 100%
In the variable d
, you have a list. List items are accessed by numeric index. For example d [0]
. But in the loop variable key
you have not numbers, but letters – a, b, c and d.