Reputation: 5
This is the data that I have: You can see that it is a dictionary with a string key and then multiple tuples to it. I am trying to write a lookup function in order to use the key string and the toll string to lookup the value (float).
dict1 = {'20MAY17': [('TOLL2', 9817.73), ('TOLL3', 8395.49)], '23MAY17': [('TOLL2', 6497.36), ('TOLL4', 6827.51)], '13MAY17': [('TOLL4', 9803.42)], '5MAY17': [('TOLL3', 6677.66)], '16MAY17': [('TOLL4', 1565.78), ('TOLL3', 7949.97), ('TOLL2', 3739.91)], '12MAY17': [('TOLL2', 5680.84)], '6MAY17': [('TOLL2', 2420.46)], '28MAY17': [('TOLL3', 6405.19), ('TOLL4', 1358.27)], '22MAY17': [('TOLL4', 4022.52), ('TOLL3', 8823.13)], '11MAY17': [('TOLL4', 4832.2699999999995)], '27MAY17': [('TOLL3', 8878.97)], '17MAY17': [('TOLL4', 4150.74)], '3MAY17': [('TOLL3', 5729.33)], '24MAY17': [('TOLL4', 1452.02), ('TOLL1', 3860.73)], '8MAY17': [('TOLL1', 9863.36)], '18MAY17': [('TOLL1', 4584.25)], '15MAY17': [('TOLL1', 8640.64)]}
The dictionary is called dict1.
Here is the function, I am using user input.
def lookup(dict1, str1, str2):
print(dict1[str1][str2])
It should do something like this:
lookup(dict1, '20MAY17', 'TOLL2')
9817.73
lookup(dict1, '20MAY17', 'TOLL3')
8395.49
Upvotes: 0
Views: 39
Reputation: 18916
Change the function to:
def lookup(dict1, str1, str2):
print(dict(dict1.get(str1)).get(str2))
This works because the dict key is converted to a dict before the 2nd key is passed.
Upvotes: 1
Reputation: 78750
Transform your data structure to a dictionary where the values dictionaries instead of lists of tuples. After that, lookup is trivial.
>>> d = {'20MAY17': [('TOLL2', 9817.73), ('TOLL3', 8395.49)], '23MAY17': [('TOLL2', 6497.36), ('TOLL4', 6827.51)]}
>>> d_better = {k:dict(v) for k,v in d.items()}
>>> d_better
{'20MAY17': {'TOLL2': 9817.73, 'TOLL3': 8395.49}, '23MAY17': {'TOLL4': 6827.51, 'TOLL2': 6497.36}}
>>>
>>> def lookup(dict_, day, toll):
... return dict_[day][toll]
...
>>> lookup(d_better, '20MAY17', 'TOLL2')
9817.73
As you can see, the lookup
function is somewhat unwarranted and you could write d_better[day][toll]
directly.
Upvotes: 1
Reputation: 1022
You can have dictionaries inside dictionaries. I would suggest to simply preprocess your data by (if your original data was stored in original_data
)
data = dict((key, dict(tpl)) for key, tpl in original_data.items())
Then you can simply do a lookup by a double item lookup:
data['20MAY17']['TOLL2']
Upvotes: 2