简体   繁体   中英

How to convert unicoded dict into a string

My issue is as follows. We have dict that has all keys and values as unicode, example:

ab = {
    u'a': u'A',
    u'b': u'B',
    u'c': u'C',
}

I want to convert it into a string. Obviously when I do:

str(ab)

I will receive:

"{u'a': u'A', u'c': u'C', u'b': u'B'}"

If I do:

unicode(ab)

I will receive:

u"{u'a': u'A', u'c': u'C', u'b': u'B'}"

My expected result is:

"{'a': 'A', 'c': 'C', 'b': 'B'}"

For the moment I found that if I do json.dumps it will convert it properly into a string without extra 'u' before each key and value, but it will also change True into true and other javascript dialect differences.

Any workaround different than iterating recursively over my data sctructure?

No, you will need to convert each item to a string manually, then string the dict, and note that unless the Unicode data happens to all be ASCII, you could run into problems. Making that assumption, you can use a dict comprehension to make it quicker and more concise:

print({str(key): str(value) for key, value in ab.items()})
{'a': 'A', 'c': 'C', 'b': 'B'}

If you are using a version of Python prior to 2.7.3, without dict comprehensions:

dict((str(key), str(value)) for key, value in ab.items())

如果您使用的是python 2.x:

dict( map(str, item) for item in ab.iteritems() )

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