python: override a single dict key based on a separate dict
This question already has an answer here:
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
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'}
链接地址: http://www.djcxy.com/p/28892.html
上一篇: 如何使用Flask更新数据库复选框的值