Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract two values from dict in python?

I'm using python3 and and i have data set. That contains the following data. I'm trying to get the desire value from this data list. I have tried many ways but unable to figure out how to do that.

slots_data = [
        {
            "id":551,
            "user_id":1,
            "time":"199322002",
            "expire":"199322002"
        },
        {
            "id":552,
            "user_id":1,
            "time":"199322002",
            "expire":"199322002"
        },
        {
            "id":525,
            "user_id":3,
            "time":"199322002",
            "expire":"199322002"
        },
        {
            "id":524,
            "user_id":3,
            "time":"199322002",
            "expire":"199322002"
        },
        {
            "id":553,
            "user_id":1,
            "time":"199322002",
            "expire":"199322002"
        },
         {
            "id":550,
            "user_id":2,
            "time":"199322002",
            "expire":"199322002"
        }
    ]
    
    
    # Desired output 
    # [
    # {"user_id":1,"slots_ids":[551,552,553]}
    # {"user_id":2,"slots_ids":[550]}
    # {"user_id":3,"slots_ids":[524,525]}
    # ]

I have tried in the following way and obviously this is not correct. I couldn't figure out the solution of this problem :

final_list = []
for item in slots_data:
    obj = obj.dict()
    obj = {
    "user_id":item["user_id"],
    "slot_ids":item["id"]
    }

    final_list.append(obj)

print(set(final_list))
like image 932
Ahmed Yasin Avatar asked Sep 11 '25 18:09

Ahmed Yasin


1 Answers

The other answer added here has a nice solution, but here's one without using pandas:

users = {}
for item in slots_data:
    # Check if we've seen this user before,
    if item['user_id'] not in users:
        # if not, create a new entry for them
        users[item['user_id']] = {'user_id': item['user_id'], 'slot_ids': []}

    # Add their slot ID to their dictionary
    users[item['user_id']]['slot_ids'].append(item['id'])

# We only need the values (dicts)
output_list = list(users.values())
like image 136
Xiddoc Avatar answered Sep 13 '25 08:09

Xiddoc