将字典中具有多个值的字典字典键映射到python中的json
我正在尝试将具有多个值的一个键的字典映射到python中.这就是我得到的.
I am trying to map a dictionary with one key that has multiple values into python. Here is what I got.
import json
list =['abe','matt','roscoe']
key="name"
nodes={}
nodes.setdefault(key,list)
['abe', 'matt', 'roscoe']
json_nodes =json.dumps(nodes)
json_nodes
'{"name": ["abe", "matt", "roscoe"]}'
但是我想要一个与此类似的json文件 [ { "name":"abe" }, { "name":"matt" }, { 名称":"roscoe" } ]
But I would like to have a json file similar to this [ { "name": "abe" }, { "name": "matt" }, { "name": "roscoe" } ]
任何建议将不胜感激.提前致谢.
Any suggestions will be greatly appreciated. Thanks in advance.
您有一个这样的名称列表
You have a list of names, like this
>>> names = ['abe', 'matt', 'roscoe']
您只需要迭代名称,并在每次迭代中创建一个新字典以获取字典列表,像这样
You just need to iterate the names, and create a new dictionary on every iteration to get the list of dictionaries, like this
>>> json.dumps([{"name": name} for name in names])
[{"name": "abe"}, {"name": "matt"}, {"name": "roscoe"}]
在这里
[{"name": name} for name in names]
称为 List Comprehension .这是生成新列表的便捷技术.在我们的例子中,我们用for name in names
遍历names
.在每次迭代中,name
将具有与该迭代相对应的当前名称,并且我们使用{"name": name}
创建一个新字典.
is called List Comprehension. It is a convenient technique to generate new lists. In our case, we iterate over names
with for name in names
. On every iteration, name
will have the current name corresponding to the iteration and we create a new dictionary with {"name": name}
.