Home > Software design >  Creating multi-input dictionary from nested lists / tuple
Creating multi-input dictionary from nested lists / tuple

Time:03-04

I have this data which is a list with nested tuple and lists: (The innerlist of 'String', Int will always contain 2 items, however the tuple sizes will vary between 1-5.

[([['Ask_Avg_Volume', '59.54232542215611'], ['Avg_Order_Insert_Size', '7.103393918685546'], 
['Avg_Order_Insert_Size', '39.40988005748331']],)]

And would like to create a dictionary out of the data which should look something like:

{Ask_Avg_Volume, 59.54232542215611: 1,
Avg_Order_Insert_Size, 7.103393918685546: 1,
Avg_Order_Insert_Size, 39.40988005748331: 1}

How can I accomplish this? I want to count the amounts of times the same string int appear, and at the same time create a multiple input (the string int) dictionary.

CodePudding user response:

You can first loop through your outer list. Then unpack the tuple one by one which would in-turn have the list. Then comes the part of iterating through that loop. Then since the inner loop contains just two items we can unpack them as s and i string and int respectively. Then we have to make combined key to keep the identifier unique. Then we check if that combined key exists in our dictionary if it does increase the count else initialise it to 1.

Here's a python sample function while implements this algorithm

def sol(items):
    a = dict()
    for tuple_row in items:
        for column in tuple_row:
            for group in column:
                [s, i] = group
                combined = '%s,%s' % (s, i)
                if combined in a:
                    a[combined]  = 1
                else:
                    a[combined] = 1
    return a
  • Related