By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,271 Members | 1,722 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,271 IT Pros & Developers. It's quick & easy.

Translation and comparison of user input, to a list using a dictionary

Jory R Ferrell
P: 62
I am having some difficulties understanding how to implement the dict() in Pyth v3.2 at least in the way that I would like to use it. Basically I first create a list. I then randomly reorganize the list. Then I want to create a dictionary using that list, assigning the indexed item from the list to a key in the dictionary. After running the program, the user is prompted to input a variable which is supposed to be equal to one of the keys of the dictionary. But I do not want the users input to be compared and weighed against the key itself, but rather the object assigned to the key (obviously...why the hell else bother creating the dictionary? :P). When I do this though, python starts complaining that variables haven't
t been declared. I thought this was the most direct way to compare the two but now I am completely stuck. No clue how to solve this.


Expand|Select|Wrap|Line Numbers
  1.  
  2. list_A = ['Obj1','Obj2','Obj3','Obj4','Obj5']
  3.  
  4. shuffle(list_A)
  5.  
  6. dict_A = {1:list_A[0], 2:list_A[1],3:list_A[2],4:list_A[3]
  7. ,5:list_A[4],6:list_A[5]}
  8.  
  9. z = input('enter something')
  10.  
  11. if dict_A[1] == list_A[0]: 
  12.     #does dict_A item '1' (i.e. list_A),
  13.     #equal the actual list_A index of 0?
  14.     print('blah,blah,blah)
  15. else:
  16.     something, something nice, something bad
  17.  
  18.  
Aug 11 '11 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 622
You would search the entire dictionary and compare the dictionary's value to the look up variable. This does not take that long unless the dictionary is huge.
Expand|Select|Wrap|Line Numbers
  1. dict_A = {1:"abc", 2:"def", 3:"ghi"}
  2. look_up = "def"
  3. for key in dict_A:
  4.     if dict_A[key] == look_up:
  5.         print "Found", key, dict_A[key] 
Aug 12 '11 #2

P: 10
Your code has some problems:
-shuffle() needs to be imported first. 'import random' should work.
-This page http://www.tutorialspoint.com/python/number_shuffle.htm says shuffle() should be called using a static 'random' object. 'random.shuffle(myList)'
-In line 7, you are asking for a 6th list item, but only 5 exist. I think thats not allowed.
-line 14 is missing a ' to end the string
Aug 18 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.