简体   繁体   中英

How to display a python-style dictionary with single backslashes in the value?

I encounter a simple but weird question. I want to display a dictionary like {'file_path': '\\11.1.2.3\\file1'} using following sentences:

>>> mydict = {'file_path': '\\\\11.1.2.3\\file1'}
>>> mydict
{'file_path': '\\\\11.1.2.3\\file1'}

I prepend r to the value string:

>>> mydict = {'file_path': r'\\11.1.2.3\file1'}
>>> mydict
{'file_path': '\\\\11.1.2.3\\file1'}

The result is same with the foregoing one, which are not expected.

Anyone can provide a method to display the dictionary, not print the value only ? Thanks in advance!

Make your own print function:

mydict = {'file_path1': r'\\11.1.2.3\file1', 'file_path2': r'\\111232.3\blabla'}
pairs = []
for k,v in mydict.items():
    pairs.append("'%s': '%s'" % (k,v))
print '{' + ', '.join(pairs) + '}'

Or if you only want one particular key.

mydict = {'file_path1': r'\\11.1.2.3\file1', 'file_path2': r'\\111232.3\blabla'}
pairs = []
for k,v in mydict.items():
    if k == 'file_path1':
        pairs.append("'%s': '%s'" % (k,v))
print '{' + ', '.join(pairs) + '}'

Using comprehension:

If you really want to convert escaped characters.

>>> import codecs
>>> mydict = {'file_path': '\\\\11.1.2.3\\file1'}
>>> print(codecs.getdecoder("unicode_escape")(str(mydict))[0])
{'file_path': '\\11.1.2.3\file1'}

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