这里的python newb ...我花了很长时间试图理解这一点,所以也许somone colud给了我一些清晰度。这是代码,我不确定第7行的工作方式。
dict = {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'four'}
letters = list(dict.keys())
print(letters)
for i in range(len(dict)):
print(dict[letters[i]]) #what is this line doing????!!!
我不确定如何阅读语法。我以为它已经进入我的信件清单并输入了“ a”,“ b”,“ c”,“ d”,但我却无法打印:
print(dict['a'])
尝试打印此内容时为什么会出现错误消息?
答案 0 :(得分:0)
dict = {'a': 'one', 'b': 'two', 'c': 'three', 'd': 'four'}
# convert the keys to a list = ['a', 'b', 'c', 'd']
letters = list(dict.keys())
print(letters)
# i is a number between 0 and the length of the dict, i.e. 4 (excluding 4)
for i in range(len(dict)):
# letters[i] = find the letter i-th letter from list `letters`, i.e. i=1 -> 'b'
# use that letter as the key and get its value, i.e. dict['b'] == 'two'
print(dict[letters[i]])
注意:
赞:
for value in d.values():
print(value)