Pur*_*ont 9 python list-comprehension utf-8
我有一本字典,我想将每个值转换为utf-8.这有效,但是有更"pythonic"的方式吗?
for key in row.keys():
row[key] = unicode(row[key]).encode("utf-8")
Run Code Online (Sandbox Code Playgroud)
我可以做的列表
[unicode(s).encode("utf-8") for s in row]
Run Code Online (Sandbox Code Playgroud)
但我不确定如何为词典做同样的事情.
这与Python Dictionary Comprehension不同,因为我不是从头开始创建字典,而是从现有字典创建字典.链接问题的解决方案没有告诉我如何遍历现有字典中的键/值对,以便将它们修改为新字典的新k/v对.下面的答案(已经被接受)显示了如何做到这一点,并且对于具有类似于我的任务的人而言,阅读/理解的内容要比关联相关问题的答案更清楚,后者更复杂.
Tha*_*Guy 12
使用字典理解.看起来你开始使用字典了:
mydict = {k: unicode(v).encode("utf-8") for k,v in mydict.iteritems()}
Run Code Online (Sandbox Code Playgroud)
字典理解的示例接近链接块的末尾.
Python 3 版本建立在 That1Guy 的那个答案之上。
{k: str(v).encode("utf-8") for k,v in mydict.items()}
Run Code Online (Sandbox Code Playgroud)
小智 5
由于我也遇到了这个问题,我构建了一个非常简单的函数,允许以 utf-8 解码任何字典(当前答案的问题是它仅适用于简单的字典)。
如果它可以帮助任何人,那就太好了,这是功能:
def utfy_dict(dic):
if isinstance(dic,unicode):
return(dic.encode("utf-8"))
elif isinstance(dic,dict):
for key in dic:
dic[key] = utfy_dict(dic[key])
return(dic)
elif isinstance(dic,list):
new_l = []
for e in dic:
new_l.append(utfy_dict(e))
return(new_l)
else:
return(dic)
Run Code Online (Sandbox Code Playgroud)