Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I wanted to convert this list of tuples into the dictionary. I am trying to convert into a dictionary. I can only convert into a dictionary if there is only one value. but I have two values in it. I will demonstrate with more details below:

     `List of tuples: [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1),

('Samsung','Tablet',10),('Sony','Handphone',100)]`

As you can see above, I am trying to identify 'Samsung' as the key and 'Handphone' and '10' as the values with respect to the key.

My desired output would be:

`Output: {'Sony': ['Handphone',100], 'Samsung': ['Tablet',10,'Handphone', 9]}`

In the above, the item 'handphone' and 'tablet' are groups according to the key values which in my case are Sony and Samsung. The quantity of the item is added/subtracted if they belong to the same item and same key (Samsung or Sony).

I would appreciate any suggestions and ideas that you guys have in order to achieve the above output. I ran out of ideas. Thank you.

1 Answer

0 votes
by (36.8k points)
edited by

Good opportunity for defaultdict

from collections import defaultdict

the_list = [

    ('Samsung', 'Handphone', 10), 

    ('Samsung', 'Handphone', -1), 

    ('Samsung', 'Tablet', 10),

    ('Sony', 'Handphone', 100)

]

d = defaultdict(lambda: defaultdict(int))

for brand, thing, quantity in the_list:

    d[brand][thing] += quantity

Result will be

{

    'Samsung': {

        'Handphone': 9, 

        'Tablet': 10

    },

    'Sony': {

        'Handphone': 100

    }

}

Do check out Python Data Science Course which helps you understand from scratch.

Related questions

Browse Categories

...