简体   繁体   English

从Python字典中将Unicode值转换为字符串

[英]Converting Unicode Values as String from a Python Dictionary

I've built a python dictionary as follows: 我已经构建了一个python字典如下:

result = {}
for fc in arcpy.ListFeatureClasses():
    for field in arcpy.ListFields(fc):
        result.setdefault(field.name, []).append(fc)

which takes the name of the fields in each table (feature class) and sets tyhem as the key value in the dictionary and goes on to set the name of the table as the value. 获取每个表(要素类)中字段的名称,并将tyhem设置为字典中的键值,然后将表的名称设置为值。 This works fine because my goal is to find out which tables have the same fields. 这很好,因为我的目标是找出哪些表具有相同的字段。 I can go on to iter over the items and print out the key, value pairs: 我可以继续讨论这些项目并打印出关键值对:

for key, value in result.iteritems():
    print key + ": " +  str(value)

which returns: 返回:

COMMENTS: [u'TM_FC', u'GT_FC', u'HG_FC', u'PO_FC', u'FU_FC'] 评论:[u'TM_FC',u'GT_FC',u'HG_FC',u'PO_FC',u'FU_FC']

I want to print out the key values as a string value instead of the unicode stuff so that it looks like this: 我想打印出键值作为字符串值而不是unicode东西,所以它看起来像这样:

COMMENTS: 'TM_FC', 'GT_FC', 'HG_FC', 'PO_FC', 'FU_FC' 评论:'TM_FC','GT_FC','HG_FC','PO_FC','FU_FC'

I've been playing around with the 'str' function and various other ways to format and convert to string, but I'm always returning the same original value list. 我一直在玩'str'函数和各种其他格式化和转换为字符串的方法,但我总是返回相同的原始值列表。 Can anyone suggest a way to accomplish what I'm looking for? 任何人都可以建议一种方法来完成我正在寻找的东西吗?

Thanks, Mike 谢谢,迈克

The issue in your code is that you are calling str(value), where value is an array. 您的代码中的问题是您正在调用str(value),其中value是一个数组。 So what happens is that the array object's __str__ function is getting invoked and it has its own way of making a string representation of the underlying values. 所以会发生的是,数组对象的__str__函数被调用,并且它有自己的方式来生成基础值的字符串表示。 This default representation uses repr to show individual elements' values. 此默认表示使用repr显示单个元素的值。 Since in this case the array elements are unicode string, you see the 'u' in the output. 因为在这种情况下数组元素是unicode字符串,所以在输出中看到'u'。

As a solution, what you want to do is to "unroll" the array manually and build up your own list representation. 作为一种解决方案,您要做的是手动“展开”数组并构建自己的列表表示。 Here's one way of doing it: 这是一种方法:

for key, value in result.iteritems():
    print key + ": " +  ",".join(["'%s'" % v for v in value])

I believe this is what you're after 我相信这就是你所追求的

for key, value in result.iteritems():
    print key + ": " +  str([ str(v) for v in value ])
result = {u'Comments':[u'TM_FC', u'GT_FC', u'HG_FC', u'PO_FC', u'FU_FC']}
for k,v in result.iteritems():
    print u'%s:%s' % (k,map(unicode.encode,v))

Simplified with string formatting, and map to change each value to a string, using the default encoding. 使用默认编码简化字符串格式化,并map以将每个值更改为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM