python3中返回字典的键

时间:2023-01-28 23:37:54

我在看《父与子的编程之旅》的时候,有段代码是随机画100个矩形,矩形的大小,线条的粗细,颜色都是随机的,代码如下,

import pygame,sys,random
from pygame.color import THECOLORS
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])
for i in range(100):
width = random.randint(0,250)
height = random.randint(0,100)
top = random.randint(0,400)
left = random.randint(0,500)
color_name = random.choice(THECOLORS.keys())
color = THECOLORS[color_name]
line_width = random.randint(1,10) pygame.draw.rect(screen,color,[left,top,width,height],line_width)
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

结果,运行出错,
TypeError: 'dict_keys' object does not support indexing

查了一下,发现这本书是基于python2.7来调试的,在python2中,key()方法返回的是一个列表,而在python3中,其返回的是一个dict_keys对象,所以我们使用random_choice来随机取一个列表元素的时候,在python3中,就不能直接使用,要使用list方法将dict_keys对象转换成列表先,

这个问题,我开始没有想到,在baidu上搜了半天,没有相关的信息,最后还是在*上面找到的答案,

原文如下,

In Python 2.x, G.keys() returns a list, but Python 3.x returns a dict_keys object instead. The solution is to wrap G.keys() with call to list(), to convert it into the correct type