在python中将unicode字符串字典转换为字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14950260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:56:31  来源:igfitidea点击:

Convert unicode string dictionary into dictionary in python

pythonunicodedictionary

提问by Sudhir Arya

I have unicode u"{'code1':1,'code2':1}"and I want it in dictionary format.

我有 unicode u"{'code1':1,'code2':1}",我想要字典格式。

I want it in {'code1':1,'code2':1}format.

我想要它的{'code1':1,'code2':1}格式。

I tried unicodedata.normalize('NFKD', my_data).encode('ascii','ignore')but it returns string not dictionary.

我试过,unicodedata.normalize('NFKD', my_data).encode('ascii','ignore')但它返回字符串而不是字典。

Can anyone help me?

谁能帮我?

采纳答案by aga

You can use built-in astpackage:

您可以使用内置ast包:

import ast

d = ast.literal_eval("{'code1':1,'code2':1}")

Help on function literal_eval in module ast:

模块 ast 中函数literal_eval 的帮助:

literal_eval(node_or_string)

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

文字评估(节点或字符串)

安全地计算表达式节点或包含 Python 表达式的字符串。提供的字符串或节点只能由以下 Python 文字结构组成:字符串、数字、元组、列表、字典、布尔值和无。

回答by pyrospade

You can use literal_eval. You may also want to be sure you are creating a dict and not something else. Instead of assert, use your own error handling.

您可以使用literal_eval. 您可能还想确保您正在创建一个 dict 而不是其他东西。而不是assert,使用您自己的错误处理。

from ast import literal_eval
from collections import MutableMapping

my_dict = literal_eval(my_str_dict)
assert isinstance(my_dict, MutableMapping)

回答by Ali-Akber Saifee

You can use the builtin evalfunction to convert the string to a python object

您可以使用内置eval函数将字符串转换为 python 对象

>>> string_dict = u"{'code1':1, 'code2':1}"
>>> eval(string_dict)
{'code1': 1, 'code2': 1}

回答by Alastair Irvine

EDIT: Turns out my assumption was incorrect; because the keys are not wrapped in double-quote marks ("), the string isn't JSON. See herefor some ways around this.

编辑:原来我的假设是不正确的;因为键没有用双引号 (") 包裹,所以字符串不是 JSON。 有关此问题的一些方法,请参见此处

I'm guessing that what you have might be JSON, a.k.a. JavaScript Object Notation.

我猜你所拥有的可能是JSON,也就是 JavaScript Object Notation。

You can use Python's built-in jsonmodule to do this:

您可以使用 Python 的内置json模块来执行此操作:

import json
result = json.loads(u"{'code1':1,'code2':1}")   # will NOT work; see above

回答by Meena Rajani

I was getting unicode error when I was reading a json from a file. So this one worked for me.

当我从文件中读取 json 时出现 unicode 错误。所以这个对我有用。

import ast
job1 = {}
with open('hostdata2.json') as f:
  job1= json.loads(f.read())

f.close()

#print type before converting this from unicode to dic would be <type 'unicode'>

print type(job1)
job1 =  ast.literal_eval(job1)
print "printing type after ast"
print type(job1)
# this should result <type 'dict'>

for each in job1:
 print each
print "printing keys"
print job1.keys()
print "printing values"
print job1.values()