How do I change all dots .
to underscores (in the dict\'s keys), given an arbitrarily nested dictionary?
What I tried is write two loops, b
Assuming .
is only present in keys and all the dictionary's contents are primitive literals, the really cheap way would be to use str()
or repr()
, do the replacement, then ast.literal_eval()
to get it back:
d ={
"brown.muffins": 5,
"green.pear": 4,
"delicious_apples": {
"green.apples": 2
} # correct brace
}
Result:
>>> import ast
>>> ast.literal_eval(repr(d).replace('.','_'))
{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}
If the dictionary has .
outside of keys, we can replace more carefully by using a regular expression to look for strings like 'ke.y':
and replace only those bits:
>>> import re
>>> ast.literal_eval(re.sub(r"'(.*?)':", lambda x: x.group(0).replace('.','_'), repr(d)))
{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}
If your dictionary is very complex, with '.'
in values and dictionary-like strings and so on, use a real recursive approach. Like I said at the start, though, this is the cheap way.