The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

This topic is READ ONLY
sandefan (39) [Avatar] Offline

after a lenghty abstinence from Python I am back again, trying to port "Hello World" samples to python3.

I have a problem with listing 16.7, p. 185, "Drawing art": after running the program I get this error message:

Traceback (most recent call last):
File "", line 21, in <module>
color_name = random.choice(THECOLORS.keys())
File "/usr/lib/python3.2/", line 252, in choice
return seq"["i"]"
TypeError: 'dict_keys' object does not support indexing

(program exited with code: 1)
Press return to continue

It is the line
color_name = random.choice(THECOLORS.keys())
that causes the problem.

Would you know how to adapt this line to python3 (version 3.2.3)?

Thank you,


P.S. I have a work-around, but is not very elegant smilie
sandefan (39) [Avatar] Offline
Re: Chapt. 16, "Drawing art": 'dict_keys' object does not support indexing!?
I found a solution to the 'dict_keys' problem, but I am too much a newbie to undertand it. Maybe somebody here can help?

user user4815162342 writes:

"You're passing the result of somedict.keys() to the function. In Python 3, dict.keys doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.
To fix the problem, use list(somedict.keys()) to collect the keys, and work with that"

How am I going to do that with the Hello World example shown in my first post above?

Thank you,

sandefan (39) [Avatar] Offline
Re: Chapt. 16, "Drawing art": 'dict_keys' object does not support indexing!?
I found a better solution for listing 16.7 with python3 (though it is still more lengthy than with python2):

import pygame, sys, random
from pygame.color import THECOLORS
keys = list(THECOLORS)
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)
line_width = random.randint(1, 5)
color_name = random.choice(keys)
color = THECOLORS[color_name]

pygame.draw.rect(screen, color, [left, top, width, height], line_width)

Anybody find something more simple?

Thank you,