'Merge if key value are the same?

roku.json

{
"Chicago":{
    "Menu":{
        "Strawberry Pie":[
            {
                "item":"Whipping Cream", 
                "container":"1 oz cup"
            },
            {
                "item":"Water" ,
                "container":"tray 1"  
            },
            {
                "item":"Cornstarch",
                "container":"tray 1"    
            },
            {
                "item":"Sugar",
                "container":"1 oz cup"
            },
            {
                "item":"fresh strawberries",
                "container":"2 oz cup"
            }
    ]
    }
}
}

my code

import json
with open('roku.json') as file: 
package_json = json.load(file)

menu = package_json['Chicago']['Menu']['Strawberry Pie']    

for i in menu:
    product = i['item']
    container = i['container']
    print(product,container)

I was wondering if someone could point to me the right direction how to concatenate if key values are the same. My current output is

Whipping Cream 1 oz cup
Water tray 1
Cornstarch tray 1
Sugar 1 oz cup
fresh strawberries 2 oz cup

and I want it to be

Whipping Cream & Sugar 1 oz cup
Water & Constarch tray 1
fresh stawberries 2 oz cup


Solution 1:[1]

If you don't want to over-complicate things, then just make another dictionary, where you'll be storing all products for all the unique containers

container2products = {}
for i in menu:
    product = i['item']
    container = i['container']
    container2products.setdefault(container, [])
    container2products[container].append(product)
for container, products_list in container2products.items():
    products_str = ' & '.join(products_list) 
    print(products_str, container)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1