I'm trying to introduce escape characters in a dictionary my_dict
filled with strings (including symbols in both the keys and values).
I know I can do this by using:
import re
map(re.escape, my_dict))
But how do I reconstitute the dictionary?
Doing this:
dict(map(re.escape, my_dict)
Gives the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 7; 2 is required
Is there a proper way to get the map()
class back into a dictionary?
CodePudding user response:
I think the issue is with map(re.escape, my_dict))
, you're adding escape characters only to the keys.
Example:
my_dict = {'hoho.ho':'merry.christmas'}
for i in map(re.escape, my_dict):
print(i)
Output:
hoho\.ho
You need to zip this with the values to create a dictionary. Try this:
new_dict = dict(zip(map(re.escape, my_dict), map(re.escape, my_dict.values())))
Output:
>>> print(new_dict)
{'hoho\\.ho': 'merry\\.christmas'}