Python Forum
Array Iteration/Merging - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Array Iteration/Merging (/thread-10920.html)



Array Iteration/Merging - Milo - Jun-13-2018

Hello All,

So let me get straight to my issue, I've got nested array which is a result set from a SQL query and has the format similar to the below.

'Resp' is the only unique column and 'ticket' often has duplicates.

[[ticket,resp,quantity]]
So for example if the array is printed (for x in x) you would get the below sample data

[56789,1326,10]
[12345,2365,1]
[56789,2542,20]
[12345,8468,5]
What I'm looking to do is add the 'quantity' field where the 'ticket' numbers are the same and produce a new nested array, the unique resp could be dropped at this point as I’m not sure if it's needed yet. The above sample data would become the below

[56789,xxxx,30]
[12345,xxxx,6]
I've tried a few things but never quite seem to get it working. Any advice or directing would be appreciated.
I hope I've been clear enough?


RE: Array Iteration/Merging - volcano63 - Jun-13-2018

This response will work for you too - just drop column 1 and use sum as an aggregation function


RE: Array Iteration/Merging - Milo - Jun-13-2018

Thanks Volcano63,

That's exactly what I'm looking for Smile

I really should have done a better job of searching.


RE: Array Iteration/Merging - buran - Jun-13-2018

well, to be honest I would alter the SQL query to get the what I want
SELECT ticket, SUM(quantity) FROM table GROUP BY ticket

data = [[56789,1326,10],
        [12345,2365,1],
        [56789,2542,20],
        [12345,8468,5]]

result = {}       
for ticket, resp, quantity in data:
    result[ticket] = result.get(ticket,0) + quantity

print(result)
or using defaultdict

from collections import defaultdict
data = [[56789,1326,10],
        [12345,2365,1],
        [56789,2542,20],
        [12345,8468,5]]

result = defaultdict(int)       
for ticket, resp, quantity in data:
    result[ticket]+=quantity

print(result)



RE: Array Iteration/Merging - Milo - Jun-13-2018

Hi Buran,

Altering my query does make a lot of sense, get the data I want and save messing with it more than I have to in Python.

Thanks for the suggestion, I'll give it a go as we