TypeError: 'dict_keys' object does not support indexing

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:

import random
outcomes = {'heads':0, 'tails':0}
sides = list(outcomes.keys())
print(sides[0])  # 输出tails


你可能感兴趣的:(Python3,dict_keys,error,python3)