Search code examples
python-3.xalgorithmsortingchatbot

Grouping data by multiply nested keys


I have some input data:

data = [('15.05.2022 12:36', 46879, 'Clinton Bill', '555-55-55', 'USA, White House', 'Cond', 'id_1', '56', 10),
        ('15.05.2022 12:36', 46879, 'Clinton Bill', '555-55-55', 'USA, White House', 'Cond', 'id_1', '56', 1),
        ('15.05.2022 12:36', 46879, 'Clinton Bill', '555-55-55', 'USA, White House', 'Lub', 'id_2', '45', 5),
        ('15.05.2022 13:00', 33990, 'Monika L.', '666-66-66', 'USA, Pennsylvania Av', 'Cond', 'id_1', '56', 7),
        ('15.05.2022 13:00', 33990, 'Monika L.', '666-66-66', 'USA, Pennsylvania Av', 'Lub', 'id_2', '45', 3),
        ('15.05.2022 13:00', 33990, 'Monika L.', '666-66-66', 'USA, Pennsylvania Av', 'Lub', 'id_2', '45', 9)]

The row items are:

(date, user_id, user_name, user_phone, user_address, product_name, product_id, product_price, product_count)

I should group data by user_id to represent info about every UNIQUE user, where count of the same products will be increminated, using python 3 script.

Smth like that:

output_data = [('15.05.2022 12:36', 46879, 'Clinton Bill', '555-55-55', 'USA, white house', ('Con', 'id_1', '56', 11), ('Lub','id_2', '45', 5)),
               ('15.05.2022 13:00', 33990, 'Monika L.', '666-66-66', 'Colorado', ('Con', 'id_1', '56', 7), ('Lub', 'id_2', '45', 12))]

Or may be you will sugest some better ways of performing output data. I'm going to send it via bot to admins.


Solution

  • I think you can group your data by unique ids and then calculate the product sum. Based on this output you can easily create your structure.

    import collections
    output_data = dict()
    
    for date, user_id, user_name, user_phone, user_address, product_name, product_id, product_price, product_count in data:
        if not output_data.get(user_id):
            output_data[user_id] = collections.defaultdict(int)
        output_data[user_id][product_id] += product_count
    
    print(output_data)