How to convert the dictionary into an array in this way

Question:

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.

Asked By: Дима

||

Answers:

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

Answered By: Jeson Pun

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]},
]
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.