Given the following dictionary, how can I return new keys that strip away all non-numbers from the keys?
import re
dict {'abc_12': 5, 'abc_1': 7, 'abc_34': 10}
for k in dict:
re.sub('[^0-9]', '', k)
# change value of first key to '12': 5
Given the following dictionary, how can I return new keys that strip away all non-numbers from the keys?
import re
dict {'abc_12': 5, 'abc_1': 7, 'abc_34': 10}
for k in dict:
re.sub('[^0-9]', '', k)
# change value of first key to '12': 5
If I understand you correctly, you want to replace the actual dictionary keys with new ones with all non-numeric characters removed.
The easiest way to do that would simply be to create a new dictionary:
new_dict = {re.sub('[^0-9]', '', k): v for k, v in my_dict.items()}
but if for some reason you absolutely need to preserve the existing one, you would need to pop each value and insert a new key with the existing value. You'd need to make sure you're operating on a static copy of the keys, otherwise the iteration would include the new values you've inserted and you'd get into all sorts of trouble.
for k in list(dict.keys()):
v = my_dict.pop(k)
new_k = re.sub('[^0-9]', '', k)
my_dict[new_k] = v
I think you're best off creating a new dictionary:
old_dict = {'abc_12': 5, 'abc_1': 7, 'abc_34': 10}
new_dict = {re.sub('[^0-9]', '', key): old_dict[key] for key in old_dict}
for key in dict iterates over the keys of the dictionary.