简体   繁体   English

从字典数据中删除 Unicode

[英]remove Unicode from Dictionary data

I have following dictionary我有以下字典

  My_Dict= { u'Apple': [u'A' , u'B'] ,u'orange': [u'C' , u'D'] }

I have another dictionary with same data but not in Unicode我有另一本具有相同数据但不是 Unicode 的字典

  Dict= { 'Apple': ['A' , 'B'] ,'orange': ['C' , 'D'] }

I am trying to compare both dictionary but its saying both dictionary are not same.我试图比较两本字典,但它说两本字典不一样。 I assume its because of that Unicode我认为它是因为那个 Unicode

Is there any way I can compare both dictionary by removing Unicode from My_dict or converting 'Dict' to Unicode ?有什么方法可以通过从 My_dict 中删除 Unicode 或将 'Dict' 转换为 Unicode 来比较两个字典?

The reason I got Unicode is because I am using S-expression parser.我得到 Unicode 的原因是因为我使用了 S 表达式解析器。 Link to parser module is below for reference.下面是解析器模块的链接以供参考。 http://sexpdata.readthedocs.org/en/latest/ http://sexpdata.readthedocs.org/en/latest/

To remove Unicode from Dictionary Try:从字典中删除 Unicode 尝试:

import json, ast
My_Dict= { u'Apple': [u'A' , u'B'] ,u'orange': [u'C' , u'D'] }
print(ast.literal_eval(json.dumps(My_Dict)))
import json
some_other_dict = json.loads(json.dumps(My_Dict))
print(some_other_dict)

Try this one.试试这个。 It will remove unicode.它将删除unicode。

Maybe perform a json.dumps on both.也许对两者都执行 json.dumps 。

json.dumps({ u'Apple': [u'A' , u'B'] ,u'orange': [u'C' , u'D'] })
Output: `'{"orange": ["C", "D"], "Apple": ["A", "B"]}'

json.dumps({ 'Apple': ['A' , 'B'] ,'orange': ['C' , 'D'] })
Output: `'{"orange": ["C", "D"], "Apple": ["A", "B"]}'`

For removing unicode you have to convert key and value from unicode.要删除 unicode,您必须从 unicode 转换键和值。

Check the below code检查下面的代码

My_Dict= { u'Apple': [u'A' , u'B'] ,u'orange': [u'A' , u'B'] }
Dict= { 'Apple': ['A' , 'B'] ,'orange': ['C' , 'D'] }

My_Dicts={}
for i, v in My_Dict.items():
  ky= i.encode('ascii','ignore')
  if type(v)is list:My_Dicts[ky]=[ item.encode('ascii') for item in v ]
  else: My_Dicts[ky] =v.encode('ascii','ignore')
My_Dict=My_Dicts

print My_Dict
print Dict

Output输出

{'orange': ['C', 'D'], 'Apple': ['A', 'B']}
{'orange': ['C', 'D'], 'Apple': ['A', 'B']}

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

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