简体   繁体   中英

How to remove single quotes only from ends of Dictionary in Python

I'm trying to take a dictionary:

{'company': 'BOOK TA .K (TAMAN DAYA) SDN BHD', 'date': '25/12/2018', 'address': 'NO.53 55,57 & 59, JALAN SAGU 18, TAMAN DAYA, 81100 JOHOR BAHRU, JOHOR.', 'total': '9.00'}

And try to remove quotes surrounding each key and value as follows (desired output):

{company:BOOK TA .K (TAMAN DAYA) SDN BHD, date:25/12/2018, address:NO.53 55,57 & 59, JALAN SAGU 18, TAMAN DAYA, 81100 JOHOR BAHRU, JOHOR., total:9.00}

The problem is that no matter which code I try (regex, strip, rstrip...), I end up snipping those single quotes that come in the middle (this is part of a large dataset and there are many cases in which the company and address fields have quotation marks as part of them ) I cannot lose these embedded single quotes , I must only get rid of those at the end. eg.

'Wendy's Stall' -> Wendy's Stall

is what I need,

NOT

'Wendy's Stall' -> Wendys Stall

I thought initially that this question is similar to what I need: Removing single quotes from a dictionary , but the problem is that they simply took integer representations of the value and got away with it as all values were numbers and not strings. Thanks a lot for your help!

If your dictionary is actually a dictionary and not just a string that looks like a dictionary, you can simply convert it into a string that looks like you want:

d = {'company': 'Wendy\'s Stall', 'date': '25/12/2018', 'address': 'NO.53 55,57 & 59, JALAN SAGU 18, TAMAN DAYA, 81100 JOHOR BAHRU, JOHOR.', 'total': '9.00'}
s = "{"+", ".join(["{}:{}".format(k,v) for k,v in d.items()])+"}"
print(s)

Output:

{company:Wendy's Stall, date:25/12/2018, address:NO.53 55,57 & 59, JALAN SAGU 18, TAMAN DAYA, 81100 JOHOR BAHRU, JOHOR., total:9.00}

Side note: If your "dictionary" is a string, you can try to convert it into an actual dict either using JSON (if it's valid JSON) or using AST.

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