2

I'm sure a question like this exists somewhere on here but I can't seem to find it. I have the following dictionary called query:

query = {'day': 0, 'item': 'Chipotle'}

And a mapping dictionary:

day_mapping = {0:2, 1:3, 2:4, 3:5, 4:6, 5:7, 6:1}

I need to override query to produce the following dictionary based on the mapping:

query = {'day': 2, 'item': 'Chipotle'}

Note query may or may not contain the key day so the following should return no error:

query = {'item': 'Chipotle'}

This is what I've come up with so far but there's gotta be a better way using list comprehension or something:

for k, v in query.items():
    if k == 'day':
        query[k] = day_mapping[v]

The reason for this is the numeric representation for days is different for python's calendar library and MongoDB's aggregation framework. Kinda annoying but I'm sure this happens all over the place.

boardrider
  • 5,882
  • 7
  • 49
  • 86
Johnny Metz
  • 5,977
  • 18
  • 82
  • 146
  • 1
    why are you looping over query.items at all? You can just do a simple `if 'day' in query` – Hamms Apr 17 '17 at 22:56
  • 2
    `if 'day' in query: query['day'] = day_mapping[query['day']]` – Patrick Haugh Apr 17 '17 at 22:57
  • You can either use some of the approaches in the dupe, or go with the EAFP approach. It depends how exceptional you expect such a case to be. If it is truly exceptional, exceptions are the way to go. – juanpa.arrivillaga Apr 17 '17 at 23:03

2 Answers2

3

Just try to replace it. This avoids one unnecessary hashing (compared to using if 'day' in query:) or looping over the dictionary and follows Pythons EAFP principle:

try:
    query['day'] = day_mapping[query['day']]
except KeyError:
    pass
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

You may use dict.get(..) to check for the presence of 'day' key in your dict as:

query = {'day': 0, 'item': 'Chipotle'}
day_mapping = {0:2, 1:3, 2:4, 3:5, 4:6, 5:7, 6:1}

day = query.get('day')  # returns `None` if 'day' key not found in `dict`
if day is not None:
    query['day'] = day_mapping[day]

Updated value of query dict in above example will be:

{'day': 2, 'item': 'Chipotle'}
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126