question 327 Decorators & Context Managers · medium
Normalise the keys a function returns
Station files from different sources call the same column Station ID, station_id or STATION-ID . Write a decorator snake_keys(func) for functions that return a dictionary: the wrapper returns a new dictionary whose keys are stripped, lower-cased, and have every run of spaces and dashes replaced by one underscore. If two keys become the same, raise ValueError. A result that isn't a dictionary is returned unchanged. The starter applies it to record(fields, values).
Decorator
snake_keys(func), with functools.wrapsKeys
" Max Temp (C) " → "max_temp_(c)"; "STATION-ID" → "station_id"; only spaces and dashes become underscoresRaises
ValueError when two keys normalise to the same nameApplied to
record(fields, values), which returns dict(zip(fields, values))Examples
callrecord(['Station ID', ' Max Temp (C) '], ['USW00094846', '31.7'])returns{'station_id': 'USW00094846', 'max_temp_(c)': '31.7'}
callrecord(['STATION-ID', 'date'], ['USW00023174', '2024-07-01'])returns{'station_id': 'USW00023174', 'date': '2024-07-01'}
callrecord(['precip_mm'], [0])returns{'precip_mm': 0}