Search code examples
pythondictionarykeyerror

Why Am I getting this key error?


enter image description hereI have no idea what im doing wrong here but I keep getting a key error, cant figure out why, what am i missing?

campers = {'pb' : 'Pooder Bennet', 'jf' : 'Jupiter Fargo',
           'rb' : 'Randy Buffet', 'bl' : 'Botany Lynn',
       'bt' : 'Boris Tortavich', 'tn' : 'Trinda Noober',
       'fj' : 'Freetus Jaunders', 'nt' : 'Ninar Tetris', 
       'gm' : 'Gloobin Marfo', 'nk' : 'Niche Kaguya',
       'bd' : 'Brent Drago', 'vt' : 'Volga Toober',
       'kt' : 'Kinser Talebearing', 'br' : 'Bnola Rae',
       'nb' : 'Nugget Beano', 'yk' : 'Yeldstat Krong',
       'gy' : 'Gelliot Yabelor', 'il' : 'Illetia Dorfson',
       'ct' : 'Can Tabber', 'tv' : 'Trinoba Vyder'}

    campers_outside_theater = random.sample(campers.keys(), 5)
    people = campers_outside_theater + ['Troid, the counselor from the bus.']
    choices = '\n\n'.join('%d. %s' % (i + 1, campers[p]) for (i, p) in enumerate(people))

Solution

  • This will give you pretty much what you want:

    import random
    campers = {'pb' : 'Pooder Bennet', 'jf' : 'Jupiter Fargo',
               'rb' : 'Randy Buffet', 'bl' : 'Botany Lynn',
           'bt' : 'Boris Tortavich', 'tn' : 'Trinda Noober',
           'fj' : 'Freetus Jaunders', 'nt' : 'Ninar Tetris', 
           'gm' : 'Gloobin Marfo', 'nk' : 'Niche Kaguya',
           'bd' : 'Brent Drago', 'vt' : 'Volga Toober',
           'kt' : 'Kinser Talebearing', 'br' : 'Bnola Rae',
           'nb' : 'Nugget Beano', 'yk' : 'Yeldstat Krong',
           'gy' : 'Gelliot Yabelor', 'il' : 'Illetia Dorfson',
           'ct' : 'Can Tabber', 'tv' : 'Trinoba Vyder'}
    
    campers_outside_theater = random.sample(campers.keys(), 5)
    people = campers_outside_theater #+ ['Troid, the counselor from the bus.']
    choices = '\n\n'.join('%d. %s' % (i + 1, campers[p]) for (i, p) in enumerate(people))
    print(choices)
    

    you had keys(people), but there is no such animal - that was your first error. It was not a KeyError, but a NameError (since keys was never defined). Then when I removed keys and just had enumerate(people) you got an actual key error because you were trying to use 'Troid, the counselor from the bus.' as a key... but it isn't one. I'm assuming you want to include him in people on the bus, but you will have to do it a different way. Perhaps include him in your campers dictionary, and always add him to your keys after you take the random sample.