Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading