简体   繁体   中英

Accessing tuples in dictionary

I have this dictionary that stores pairs of two quiz scores and participants' ID. The structure is {(quiz1, quiz2): ID}

scoredict = {('83', '93'): '81937', ('88', '86'): '33576', ('96', '97'): '01084', 
('81', '95'): '48534', ('84', '72'): '11235', ('77', '80'): '01835', ('90', '83'): 
'39488', ('75', '74'): '31049', ('80', '62'): '10188', ('85', '86'): '63011', 
('66', '89'): '58272'}

I want to make this program to look up for an ID by entering a pair of quiz scores. Like, for example, if the user input 83 and 93 for quiz 1 and quiz 2, it will return 81937. I've been working on this since the last 48 hours, but none of my codes worked...

And is it possible to find the closest available scores for both quizzes and print the ID?

I verified your solution already works with ipython :

In [1]: scoredict = {('83', '93'): '81937', ('88', '86'): '33576', ('96', '97'): '01084', 
   ...: ('81', '95'): '48534', ('84', '72'): '11235', ('77', '80'): '01835', ('90', '83'): 
   ...: '39488', ('75', '74'): '31049', ('80', '62'): '10188', ('85', '86'): '63011', 
   ...: ('66', '89'): '58272'}

In [2]: scoredict['83','93']
Out[2]: '81937'

For the closest scores, you can try this:

test = (83, 93)

deviation = float('inf')
best_match = None

for score1, score2 in scoredict:
  error = abs(int(score1) - test[0]) + abs(int(score2) - test[1])

  if error < deviation:
    deviation = error
    best_match = (score1, score2)

print scoredict[best_match]

只需做:

>>> scoredict[(score1,score2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM