Reputation: 95
I am taking a data set with each entry classified with a numeric code. Only the first 2-digits are needed, so I'm summing based on just those.
sum_dict = {
k: sum(item[1] for item in g)
for k, g in groupby(sorted(
source_data.items()), key=lambda item: item[0][:2])
}
There's a known number of categories, but all categories are not necessarily used in every instance. The sum_dict
will only have entries for the 2-digit category if it appeared in the source data.
sum_dict = {
'12': 15,
'29': 3,
'33': 22,
}
I want to change all the keys in sum_dict
to be more descriptive, so I am deleting each key and replacing it with a more descriptive one. However, there will be a key error if a particular instance of the dictionary does not use a key that I then rename ('65' in this example).
if '12'in sum_dict:
sum_dict['12: Alpha'] = sum_dict.pop('12')
if '29'in sum_dict:
sum_dict['29: Beta'] = sum_dict.pop('29')
if '33'in sum_dict:
sum_dict['33: Gamma'] = sum_dict.pop('33')
if '65'in sum_dict:
sum_dict['65: Delta'] = sum_dict.pop('65')
I added the if
checks so I could rename all possible keys even if they don't exist every time, but it seems inefficient (and harder to read) to have dozens of ifs to do this task. Am I missing a better way of doing this?
Upvotes: 0
Views: 177
Reputation: 1122312
Create a mapping for your names:
better_names = {'12': 'Alpha', '29': 'Beta', '33': 'Gamma', '65': 'Delta'}
Now you can use these when producing your initial dictionary, no renaming needed:
sum_dict = {
'{}: {}'.format(k, better_names[k]): sum(item[1] for item in g)
for k, g in groupby(sorted(
source_data.items()), key=lambda item: item[0][:2])
}
However, if you must rename later on, you can use that same dictionary in a loop:
for key, name in better_names.items():
if key in sum_dict:
sum_dict['{}: {}'.format(key, name)] = sum_dict.pop(key)
Upvotes: 1
Reputation: 973
variable_array = [("12", "Alpha"),("29", "Beta") ... ("65","Delta")]
for number, var in variable_array:
if number in sum_dict:
sum_dict["{}: {}".format(number, var)] = sum_dict.pop(number)
This should do what you want
Upvotes: 2