TypeError: 'dict_keys' object does not support indexing

[python] view plain copy
print ?
  1. import random  
  2. outcomes = {’heads’:0‘tails’:0}  
  3. sides = outcomes.keys()  
  4. print(sides[0])  
import random
outcomes = {'heads':0, 'tails':0}
sides = outcomes.keys()
print(sides[0])

会产生错误:TypeError: ‘dict_keys’ object does not support indexing

这是由于python3改变了dict.keys,返回的是dict_keys对象,支持iterable 但不支持indexable,我们可以将其明确的转化成list:

[python] view plain copy
print ?
  1. import random  
  2. outcomes = {’heads’:0‘tails’:0}  
  3. sides = list(outcomes.keys())  
  4. print(sides[0])  # 输出tails  
import random
outcomes = {'heads':0, 'tails':0}
sides = list(outcomes.keys())
print(sides[0])  # 输出tails


你可能感兴趣的:(python2,python3,dict-keys,Python)