user1679288
user1679288

Reputation: 13

Type Error when Randomize Dictionary in Python

I was making a simple flash card program to build my vocabulary, and thus needed to randomize a dictionay I found many helpful answers on this site, many off this site, and noticed that shuffle was an option (i know there was random.choice, but i went with shuffle) but there's something that I'm not grasping. looks like this:

import random

vocab_dict = {'word1':'def1',
           'word2':'def2',
           'etc.':'etc.'}

vocab_dict_rand = vocab_dict.keys()  
random.shuffle(vocab_rand)           **#<--This is where problem occurs**

for key in vocab_rand:
      print word
      input ""
      print definition
      input ""

input exit

So the program crashes and points to that line with the random.shuffle(vocab_rand)...

I get this in the shell

  File "C:\Python31\lib\random.py", line 270, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'dict_keys' object does not support indexing

Any help would be appreciated.

Upvotes: 1

Views: 794

Answers (2)

nneonneo
nneonneo

Reputation: 179422

In Python 3, dict.keys() returns a special dict_keys object that only acts like a list -- it's not a real list, so you can't index into it or shuffle it (it should be used only for iteration).

Instead, use vocab_rand = list(vocab_dict.keys()).

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251378

In Python 3, keys returns an iterator, not a list. You need to have a list to shuffle. Use vocab_dict_rand = list(vocab_dict.keys()).

Upvotes: 1

Related Questions