Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 dimensional dictionary

subjects = {
    0:9,'fail': 0,
   9:14, 'pass': 25,
   15:17, 'merit': 40,
    18:20,'Distinction': 50
}

I want the dictionary above to contain 3 dimensions. user input will be between the initial numbers. depending what number the user enters the following message should be displayed. eg. 4 is a fail worth 0 points , 10 is a pass worth 25 points and so on.

inputs = ['irish','english','french','italian','dutch','german']
for i in range(1, 7):
    inputs.append(raw_input('Enter mark for {}: '.format(i)))

I want the loop to ask enter mark for irish etc

print sum(subjects[name][value] for name in inputs)

Can this be done?

like image 878
miguel Avatar asked Jan 08 '13 21:01

miguel


1 Answers

A dictionary stores its values based on a hash of the keys.

This means a dictionary lookup only returns entries whose keys exactly match the one used in the lookup.

You cannot have a key be "any number in the range 3 to 5" and expect a lookup for "4" to hit.

However, what you can do is duplicate the dictionary entries:

subject_ranges = [(0, 8, 'fail', 0),
                  (9, 14, 'pass', 25),
                  (15, 17, 'merit', 40),
                  (18, 20, 'Distinction', 50)]
subjects = {}
for low, high, descr, points in subject_ranges:
   for score in range(low, high+1):
      subjects[score] = {'description': descr, 'value': points}

And collect the input like this:

input_names = ['irish','english','french','italian','dutch','german']
scores = []
for i in range(len(input_names)):
    scores.append(int(raw_input('Enter mark for %s: ' % input_names[i])))

Now this code will work to print the total score as you wished:

print sum(subjects[score]['value'] for score in scores)

This is not a "3-dimensional dictionary", nor anything like it. It's a dictionary whose keys are integers and whose values are two-element dictionaries (you could use NamedTuple if you wished). But from your question, it doesn't look like you actually needed anything more sophisticated than this.

like image 104
Borealid Avatar answered Sep 23 '22 23:09

Borealid