转换字典键的最快方法从 str 到 Unicode 的值? [英] Fastest way to convert a dict's keys & values from str to Unicode?
本文介绍了转换字典键的最快方法从 str 到 Unicode 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一个计数器 from collections import Counter
,我想使用 matplotlib.pylot
打印它的值.
I'm working with a counter from collections import Counter
and I want to print its values using matplotlib.pylot
.
当我尝试使用:
plt.bar(range(len(cnt)), cnt.values(), align='center')
plt.xticks(range(len(cnt)), cnt.keys())
plt.show()
我收到以下错误:
ValueError: matplotlib 显示文本必须包含所有代码点 <128 或使用 Unicode 字符串
ValueError: matplotlib display text must have all code points < 128 or use Unicode strings
这就是我尝试将 Counter 字典键转换为 Unicode 的原因.
That's why I'm trying to convert the Counter dictionary keys to Unicode.
推荐答案
如果您使用的是 Python 2.7,则可以使用 dict comprehension:
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()}
对于旧版本:
unidict = dict((k.decode('utf8'), v.decode('utf8')) for k, v in strdict.items())
(当然,这假设您的字符串是 UTF-8 格式.)
(This assumes your strings are in UTF-8, of course.)
这篇关于转换字典键的最快方法从 str 到 Unicode 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文