Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

How to select a random key from a dictionary

dictionary random key demand

Best Answer Flying Dutchman, 24 April 2013 - 05:25 AM

They've changed slightly how dictionaries work in Python 3, dict_keys no longer support indexing. You'll have to convert keys / values to list. Source.

Go to the full post


This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1 Bissy

Bissy

    CC Regular

  • Member
  • PipPipPip
  • 47 posts

Posted 24 April 2013 - 03:48 AM

Sup guys, am making a Who'sWho game and i need my program to select a random key from and dictionary, all the other solutions require me to convert the dictionary into a list first, but then this solution runins the hwole program. AM using python 3.3.0 btw.

 

Example  = {"Hello":"Canada", "Bye":"America}

 

how would i get a random key form that dictionary

 

thanks guys in advance!



#2 sepp2k

sepp2k

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 183 posts

Posted 24 April 2013 - 04:19 AM

but then this solution runins the hwole program.

 
What do you mean by that? How does it ruin it?
 

Example  = {"Hello":"Canada", "Bye":"America}
 
how would i get a random key form that dictionary

random.choice(Example.keys())

Edited by sepp2k, 24 April 2013 - 04:19 AM.


#3 Flying Dutchman

Flying Dutchman

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1090 posts

Posted 24 April 2013 - 05:25 AM   Best Answer

They've changed slightly how dictionaries work in Python 3, dict_keys no longer support indexing. You'll have to convert keys / values to list. Source.


The roots of education are bitter, but the fruit is sweet.


#4 sepp2k

sepp2k

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 183 posts

Posted 24 April 2013 - 05:33 AM

Ah, sorry, my bad.



#5 Bissy

Bissy

    CC Regular

  • Member
  • PipPipPip
  • 47 posts

Posted 24 April 2013 - 07:03 AM

No problem and thanks Flying Dutchman






Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download