简体   繁体   English

如果键值相同则合并?

[英]Merge if key value are the same?

roku.json 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我现在的output是

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM