[英]Converting an list to a dictionary in python
I'm trying to convert a list that is in the form of a dictionary to an actual dictionary. 我正在尝试将字典形式的列表转换为实际字典。
This is for a webs scraping tool. 这是用于刮网工具。 I've tried removing to the single
''
and setting as a dictionary, but I am new to programming and I think my logic is off in some way. 我已经尝试删除单个
''
并设置为字典,但我是编程的新手,我认为我的逻辑在某种程度上是关闭的。
My list is of the form 我的清单是表格
['"name":"jack"', '"address":"1234 College Ave"']
I am trying to convert general form to a dictionary of the form 我正在尝试将一般表单转换为表单的字典
{"name":"jack", "address":"1234 College Ave"}
You can convert it to a string JSON representation then use json.loads
. 您可以将其转换为字符串JSON表示,然后使用
json.loads
。
>>> import json
>>> data = ['"name":"jack"', '"address":"1234 College Ave"']
>>> json.loads('{' + ', '.join(data) + '}')
{'name': 'jack', 'address': '1234 College Ave'}
l = ['"name":"jack"', '"address":"1234 College Ave"']
d = {elem.split(":")[0][1:-1]:elem.split(":")[1][1:-1] for elem in l}
print(d)
One way to tackle this is to fix each individual string before passing it to json.loads. 解决此问题的一种方法是在将每个字符串传递给json.loads之前修复它们。
inp = ['"name":"jack"', '"address":"1234 College Ave"']
import json
result = {}
for item in inp:
result.update(json.loads("{" + item + "}"))
print(result)
{'name': 'jack', 'address': '1234 College Ave'}
However, ideally you should be getting data in a better format and not have to rely on manipulating the data before being able to use it. 但是,理想情况下,您应该以更好的格式获取数据,而不必依赖于在使用数据之前操纵数据。 Fix this problem "upstream" if you can.
如果可以的话,修复此问题“上游”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.