Fastest way to convert a dict's keys & values from str to Unicode?

前端 未结 2 488
遇见更好的自我
遇见更好的自我 2020-12-19 13:35

I\'m working with a counter from collections import Counter and I want to print its values using matplotlib.pylot.

When I try to do it usin

相关标签:
2条回答
  • 2020-12-19 13:46

    So, i thought the op asked for unicode, not for UTF-8. Unicode is not an encoding, it's just actual text. So would this not be more accurate and/or readable?

    unidict = {unicode(k): unicode(v) for k, v in strdict.items()}
    
    0 讨论(0)
  • 2020-12-19 13:52

    If you're using Python 2.7, you can use a dict comprehension:

    unidict = {k.decode('utf8'): v.decode('utf8') for k, v in strdict.items()}
    

    For older versions:

    unidict = dict((k.decode('utf8'), v.decode('utf8')) for k, v in strdict.items())
    

    (This assumes your strings are in UTF-8, of course.)

    0 讨论(0)
提交回复
热议问题