[英]convert list of dict to dict of dict
How could in convert a list of dict
to a dict
of dict
. 怎么能名单中转换
dict
的dict
的dict
。
This is the list I have: 这是我的清单:
data = [{'id': '7249722264','title':'test'}, {'id': '111','test':'te11111st'}]
I have to pass this dataset to an api that accept data in this format: 我必须将此数据集传递给接受此格式数据的api:
api_data = {'fields': {'id': '72497264', 'title': 'test'}}
I need to loop through the element present in the data list and pass it to api like this: 我需要遍历数据列表中存在的元素,并将其传递给api,如下所示:
for each record in the list: 对于列表中的每个记录:
new_dict = {'fields': {'id': '72497264', 'title': 'test'}}
api.post(new_dict)
How I can achieve this? 我该如何实现? Thanks
谢谢
You can do it like so with a for
loop: 您可以使用
for
循环来做到这一点:
data = [{'id': '7249722264','title':'test'}, {'id': '111','test':'te11111st'}]
new_dict = {}
for e, i in enumerate(data):
new_dict['fields'+str(e)] = i
print(new_dict)
>>> {'fields0': {'id': '72497264', 'title': 'test'}, 'fields1': {'id': '111','test':'te11111st'}}
But you can't name every key fields
because dict keys are unique, so you would have to either make the API call each time inside the for
loop, or as I've done above append an index to the key name. 但是您不能为每个键
fields
命名,因为dict键是唯一的,因此您必须每次在for
循环内都进行API调用,或者像上面我所做的那样在键名后附加一个索引。
Edit: Alternative dict comprehension (courtesey of Dillon Davis): 编辑:替代dict理解(狄龙·戴维斯的同道):
data = [{'id': '7249722264','title':'test'}, {'id': '111','test':'te11111st'}]
new_dict = {'fields{}'.format(i):x for i, x in enumerate(data)}
print(new_dict)
>>> {'fields0': {'id': '72497264', 'title': 'test'}, 'fields1': {'id': '111','test':'te11111st'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.