最快的方式来转换一个dict的密钥&从str到Unicode的值? [英] Fastest way to convert a dict's keys & values from str to Unicode?

查看:169
本文介绍了最快的方式来转换一个dict的密钥&从str到Unicode的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个计数器从集合导入计数器,我想打印其值使用 matplotlib.pylot



当我尝试使用:

  plt .bar(range(len(cnt)),cnt.values(),align ='center')
plt.xticks(range(len(cnt)),cnt.keys())
plt .show()

我收到以下错误:


ValueError:matplotlib显示文本必须具有所有代码点< 128或使用Unicode字符串


这就是为什么我试图将Counter字典键转换为Unicode。

解决方案

如果您使用的是Python 2.7,您可以使用dict的理解:

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

对于旧版本:

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

(这当然假定你的字符串是UTF-8。)


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 using:

plt.bar(range(len(cnt)), cnt.values(), align='center')
plt.xticks(range(len(cnt)), cnt.keys())
plt.show()

I get the following error:

ValueError: matplotlib display text must have all code points < 128 or use Unicode strings

That's why I'm trying to convert the Counter dictionary keys to Unicode.

解决方案

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.)

这篇关于最快的方式来转换一个dict的密钥&amp;从str到Unicode的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆