1

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
1
  • 3
    You can't have duplicate keys. How do you want to handle that issue? Commented Aug 20, 2014 at 21:04

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

1

You do not need a regex:

>>> di={'abc_12': 5, 'abc_1': 7, 'abc_34': 10}
>>> {''.join(c for c in k if c in '0123456789'):v for k, v in di.items()}
{'1': 7, '12': 5, '34': 10}

Comments

1

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}

2 Comments

are you sure that you're iterating over keys in that loop?
Pretty sure - for key in dict iterates over the keys of the dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.