1

I am learning random function on Python 3 with this example, getting an error as the post title. 'dict_keys' object is not subscriptable. I am not sure where i did wrong with dictionary.

import random
outcomes = {
        'heads':0, 
        'tails':0
        }

sides = outcomes.keys()

for i in range(100):
    outcomes[random.choice(sides)] += 1

print("Heads:", outcomes['heads'])
print("Tails:", outcomes['tails'])

Below is the error output

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-f58aad35f1b0> in <module>
      8 
      9 for i in range(100):
---> 10     outcomes[random.choice(sides)] += 1
     11 
     12 print('Heads:', outcomes['heads'])

C:\ProgramData\Anaconda3\lib\random.py in choice(self, seq)
    260         except ValueError:
    261             raise IndexError('Cannot choose from an empty sequence') from None
--> 262         return seq[i]
    263 
    264     def shuffle(self, x, random=None):

TypeError: 'dict_keys' object is not subscriptable
Root Loop
  • 3,004
  • 9
  • 46
  • 72
  • What line is the error on? – clubby789 Oct 13 '19 at 01:29
  • 2
    Possible duplicate of [NLTK python error: "TypeError: 'dict\_keys' object is not subscriptable"](https://stackoverflow.com/questions/26394748/nltk-python-error-typeerror-dict-keys-object-is-not-subscriptable) Do `random.choice(list(sides))` – AmourK Oct 13 '19 at 01:30
  • @AmourK yes, it is a " list ". I accept your answer. – Root Loop Oct 13 '19 at 01:34

1 Answers1

9

choices picks a number in the range of the size of the list passed as argument, and then tries to return the element at that index.

keys() return a set, which doesn't have indexes.

You need a list to use choice:

sides = list(outcome.keys())

njzk2
  • 38,969
  • 7
  • 69
  • 107