Why does double backslash not work in python dictionary

Question:

I have a python dictionary that holds connection details like so:

x = {
  'myserver' : {
    'DSN': 'servername',
    'DATABASE': 'mydatabase',
    'UID': 'myusername',
  'PWD': 'my\password'
    }
}

I expected the PWD value to be mypassword but I get my\password instead.

As a string on its own works i.e.

pwd = 'my\password'
# returns mypassword

So I tried this (but still doesn’t work):

pwd = 'my\password'
x = {
  'myserver' : {
    'DSN': 'servername',
    'DATABASE': 'mydatabase',
    'UID': 'myusername',
  'PWD': pwd
    }
}

Also tried four backslashes \\, tried just one backslash (got an error), tried putting r in front of string value and a combination of them, still nothing…

Essentially expecting the output of the dictionary to display/hold/point to mypassword and not my\password

Asked By: AK91

||

Answers:

How do you verify that it does not work?
Using the print function you can see that it does exactly what you expect:

x = {
  'myserver' : {
    'DSN': 'servername',
    'DATABASE': 'mydatabase',
    'UID': 'myusername',
  'PWD': 'my\password'
    }
}

print(x)

print(x['myserver']['PWD'])

Outputs:

{'myserver': {'DSN': 'servername', 'DATABASE': 'mydatabase', 'UID': 'myusername', 'PWD': 'my\password'}}

and

mypassword
Answered By: tomanizer

This "problem" is essentially down to how you call 'PWD'‘s value in your code. Simply printing the dictionary whole will not process the backslash, or r string, or whatever you use to escape your backslash character, for that matter. That’s why you get 2 backslashes when you call the whole dictionary. Note – even making it an r string won’t change this, because an r string goes through and adds an extra backslash behind every backslash to automatically escape it.

However, when you call it specifically i.e. x['myserver']['PWD'], the escapes in that string will be processed, because it is being called, treated and thus processed as a single string and all the escapes in the string will be processed.

To summarise, if you call the whole dictionary, or even the nested inner dictionary, the string will not be processed, and so \ will appear wherever you want . To get the output mypassword, call the value specifically, like x['myserver']['PWD'].

Answered By: Arvind Raghu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.