It is necessary that the dictionary of the form
# input
items_dict = {
123: [1, 2, 3],
456: [1, 2, 3, 4],
678: [1, 2]
}
was converted to the following array
# output
[
{'item_ids': [123, 456], 'users_ids': [3]},
{'item_ids': [456], 'users_ids': [4]},
{'item_ids': [123, 456, 678], 'users_ids': [1, 2]}
]
The logic is as follows, I have an item_dict dictionary, the item_id key is the id of the house, the value of users_ids is the id of the users to send the letter to, I want to convert this into an array of dictionaries, item_ids is an array of houses, users_ids is an array of users, I want to do this in order to send the same letter to several users at once, and not individually, to reduce the number of requests.
CodePudding user response:
Try:
def squeeze(d):
tmp = {}
for k, v in d.items():
for i in v:
tmp.setdefault(i, []).append(k)
out, b = {}, tmp
while tmp:
k, *rest = tmp.keys()
out[k], new_keys = [k], []
for kk in rest:
if tmp[kk] == tmp[k]:
out[k].append(kk)
else:
new_keys.append(kk)
tmp = {k: tmp[k] for k in new_keys}
return [{"item_ids": b[k], "user_ids": v} for k, v in out.items()]
items_dict = {123: [1, 2, 3], 456: [1, 2, 3, 4], 678: [1, 2]}
print(squeeze(items_dict))
Prints:
[
{"item_ids": [123, 456, 678], "user_ids": [1, 2]},
{"item_ids": [123, 456], "user_ids": [3]},
{"item_ids": [456], "user_ids": [4]},
]
CodePudding user response:
items_dict = {
123: [1, 2, 3],
456: [1, 2, 3, 4],
678: [1, 2]
}
mylist=[]
for key in items_dict:
mylist =items_dict[key]
print(mylist)
hope this will help, please reply me if it's not right