0

I am trying to create a list that holds dictionaries of randomly generated colors. So for instance, the first dictionary of the list would be color 0 with values of 255, 255, 255. I am getting a syntax error with the "color{x}" where python is saying that it should be an integer or a splice, but not a string. Removing the color part gives me another error where python is saying the set object has no format attribute.

This is using pygame 1.9.4 and python 3.7 and I am rather new to python programming in general. I have tried messing with the "color{x}" part, but this previous thread had something similar that work for them, so I just copied the syntax to see if I could get it to work.

colors = []
colorLength = len(colors)
for x in range(3):
    colors["color{x}".format(x)]= random.randint(0,255), 
           random.randint(0,255), random.randint(0,255)
    #colors.append()
else:
    print(colorLength)

I am trying to get the list colors to hold 3 dictionaries (at the moment, plan on expanding the list when I get it working), that hold a randomly generated color.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Brehmly
  • 35
  • 1
  • 4

2 Answers2

0

You are confusing list with dictionary - a list is simply that ... a list - an indexable collection of things . What you need is a dictionary - something that stores a value under a key . Dictionarys are created by: colors = {}.

The other error you get is from using str.format() with a named parameter -you can omit the x or fix it like this:

for xxx in range(3):
    # x is the name inside the {x} and it should be replaced by xxx
    colors["color{x}".format( x = xxx)] = ...

if you just use

for xxx in range(3):
    colors["color{}".format(xxx)] = ...

format will replace positionally .. the 1st {}placeholder is replaced with the 1st value in format( 1st, 2nd, ...) etc.

Readup:


Fixed code:

import random 

colors = {} # create empty dictionary

for x in range(3):
    # random.choices creates k random values from the given iterable in one go
    colors["color{}".format(x)] = random.choices(range(0,256), k =3) 

print(colors) 

Output:

{'color0': [189, 5, 3], 'color1': [57, 218, 56], 'color2': [64, 150, 255]}

Doku:


If you really need tuples, you can use tuple( random.choices(range(0,256), k =3) )

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

If I understand correctly you actually want a dictionary of tuples. Something like this:

import numpy as np
a = {i: tuple(np.random.randint(256, size=3)) for i in range(3)}

print(a)
{0: (65, 168, 140), 1: (193, 85, 66), 2: (28, 25, 7)}
TPereira
  • 138
  • 6
  • I am always astonished what numpy is good for :) pulling it in for random numbers when nothing else uses numpy is a bit mucht though. – Patrick Artner Jan 29 '19 at 22:07
  • yeah, sorry eheh. Work with numpy everyday nowadays, so it is easy to fall in some overkills with it :) – TPereira Jan 29 '19 at 22:25