Home > other >  Trying to pull random items from a nested dictionary
Trying to pull random items from a nested dictionary

Time:02-05

I'm new, I've only been learning for a week now. I've been looking through online resources and now I'm trying to make a small cat generator, I can get it to randomize the breeds like I want but I can't get it to give me the color, coat length, pattern

import random

breeds = {
    'bengal': {
        'colors' : ['red', 'black', 'grey'],
        'length': ['short', 'medium', 'long'],
        'pattern': ['spotted', 'marbled']
        },
    'tabbycat': {
        'colors' : ['grey', 'blue', 'silver'],
        'length' : ['short', 'medium', 'long'],
        'pattern' : ['mackeral', 'classic']
        }
    }

breed = random.choice(list(breeds))
color = random.choice(list(breeds['colors']))


print(breed.title())
print(color.title())


This code tells me KeyError: 'colors', I've also seen 'colors' not defined, so i'm having issues accessing the nested bits and I'm not sure why.

CodePudding user response:

The list(breeds) function just gives you this: ['bengal', 'tabbycat'], which clearly does not have "colours" in it.

Think about how dictionaries are accessed - dictionaries have a key that holds a value. You would need to access the "colors" key which is inside a dictionary inside another dictionary, meaning you would need two keys - the first being the breed (chosen by the line breed = random.choice(list(breeds)), and the second key being "colors" (returns the list of possible colours).

A fixed version including coat length and pattern might look something like this:

import random

breeds = {
    'bengal': {
        'colors' : ['red', 'black', 'grey'],
        'length': ['short', 'medium', 'long'],
        'pattern': ['spotted', 'marbled']
        },
    'tabbycat': {
        'colors' : ['grey', 'blue', 'silver'],
        'length' : ['short', 'medium', 'long'],
        'pattern' : ['mackeral', 'classic']
        }
    }

breed = random.choice(list(breeds))
color = random.choice(breeds[breed]["colors"])
coat_length = random.choice(breeds[breed]["length"])
pattern = random.choice(breeds[breed]["pattern"])

print(breed.title())
print(color.title())
print(coat_length.title())
print(pattern.title())
  • Related