简体   繁体   中英

convert list of dict to dict of dict

How could in convert a list of dict to a dict of 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_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:

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:

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.

Edit: Alternative dict comprehension (courtesey of Dillon Davis):

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'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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