简体   繁体   中英

KeyError: Backslash in Python Dictionary Key

I am trying in Python to retrieve values from a dictionary created with json.loads() from the .text of a requests object which uses:

'\/' 

as a separator in some of the dictionary keys. The dictionary is the standard output from another program not under my control.

If I try using:

dictionary['text\/text']

It generates a KeyError and says that there is no

'text\\/text'

key. Notice the double backslash it inserted.

I have tried:

r'text\/text', 'text\\/text', 'text'+chr(92)+chr(47)+'text', etc

I can't seem to get this to work. There's got to be some way to do this without having to parse the text of the entire dictionary and replace all occurrences of '/'. Any ideas?

edit: This was a stupid mistake on my part. I was reading the key values from the request.text, in which an extra backslash was printed before the forward slash. Martijn Pieters' comment hit straight home to the problem.

I tried it in Idle (2.7.6) and it looks valid:

>>> d={'text\/text':'test'}
>>> d
{'text\\/text': 'test'}
>>> d['text\/text']
'test'
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM