将每个字典值转换为utf-8(字典理解力?) [英] Convert every dictionary value to utf-8 (dictionary comprehension?)
问题描述
我有一本字典,我想将每个值都转换为utf-8.这行得通,但是有更pythonic"的方式吗?
I have a dictionary and I want to convert every value to utf-8. This works, but is there a "more pythonic" way?
for key in row.keys():
row[key] = unicode(row[key]).encode("utf-8")
我可以做的清单
[unicode(s).encode("utf-8") for s in row]
但是我不确定如何对字典做同样的事情.
but I'm not sure how to do the equivalent thing for dictionaries.
这与 Python字典理解不同,因为我不是想从头开始创建字典,但来自现有字典.链接问题的解决方案没有向我展示如何遍历现有字典中的键/值对,以便将其修改为新字典的新k/v对.下面的答案(已被接受)显示了该方法的实现,并且与具有类似链接的相关问题的答案相比,对于具有类似于我的任务的某人而言,其阅读/理解要清晰得多.
This is different from Python Dictionary Comprehension because I'm not trying to create a dictionary from scratch, but from an existing dictionary. The solutions to the linked question do not show me how to loop through the key/value pairs in the existing dictionary in order to modify them into new k/v pairs for the new dictionary. The answer (already accepted) below shows how to do that and is much clearer to read/understand for someone who has a task similar to mine than the answers to the linked related question, which is more complex.
推荐答案
使用字典理解.看来您是从字典开始的,所以:
Use a dictionary comprehension. It looks like you're starting with a dictionary so:
mydict = {k: unicode(v).encode("utf-8") for k,v in mydict.iteritems()}
字典理解的示例在链接中该块的末尾附近.
The example for dictionary comprehensions is near the end of the block in the link.
这篇关于将每个字典值转换为utf-8(字典理解力?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!