0

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 my\password but I get my\\password instead.

As a string on its own works i.e.

pwd = 'my\\password'
# returns my\password

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 my\password and not my\\password

AK91
  • 671
  • 2
  • 13
  • 35
  • If you write the string literal `'my\\password'` then you get the string `my\password`. If you're seeing two backslashes, that's down to how you're viewing it or something else you're doing with the string. Try `print(x['myserver']['PWD'])`. – khelwood Jul 31 '20 at 10:04
  • https://stackoverflow.com/a/3380867/5881796 – Wereii Jul 31 '20 at 10:05
  • The issue is the same with dicts as with tuples, hence the linked duplicate. – Karl Knechtel Aug 07 '22 at 03:45

2 Answers2

3

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 my\password, call the value specifically, like x['myserver']['PWD'].

Arvind Raghu
  • 408
  • 3
  • 9
2

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

my\password
tomanizer
  • 851
  • 6
  • 16
  • smh you're correct. So when I unpack the dictionary when connecting to the db I get an error but that would be a totally different issue/question. – AK91 Jul 31 '20 at 10:10