简体   繁体   English

通过对值求和对嵌套字典进行排序 python pandas

[英]Sort in nested dict by summing values python pandas

I have nested dict something like that我嵌套了类似的字典

my_dict=  {'name1': {'code1': {'brand1': 2}},'name2': {'code2.1': {'brand2.1': 2,'brand2.2': 8,'brand2.3': 5, 'brand2.4': 4},'code2.2': {'brand2.1': 2, 'brand1': 1, 'brand2.5': 25}},'name3': {'code1': {'brand2.1': 2},'code3': {'brand4': 1,'brand3.1':2}}}    

I need sort on the level "code" with depending on summing values "brands".我需要根据求和值“品牌”对“代码”级别进行排序。 For example,例如,

target_dict=  {'name1': {'code1': {'brand1': 2}}, 'name2': {'code2.2': {'brand2.1':2,'brand1': 1,'brand2.5': 25},'code2.1': {'brand2.1': 2,'brand2.2': 8,'brand2.3': 5,'brand2.4': 4}}, 'name3': {'code3': {'brand4': 1, 'brand3.1':2},'code1': {'brand2.1': 2}}}    

* # 'code2.2' first because 2+1+25=28 > 2+8+5+4=19 # 'code3' first because 1+2=3 > 2 * # 'code2.2' 先是因为 2+1+25=28 > 2+8+5+4=19 # 'code3' 先是因为 1+2=3 > 2

I can sum values "brands" by "code" with我可以通过“代码”对价值“品牌”求和

sum_values = [[[i, sum(v[i].values())] for i in v.keys()] for x,y in v.items() for k,v in my_dict.items()]

and try combine with sort function as并尝试结合排序 function 作为

target_dict = sorted(my_dict.items(), key=lambda i: [[[i, sum(v[i].values())] for i in v.keys()] for x,y in v.items() for k,v in my_dict.items()], reverse=True).

Thanks for your attention and help!感谢您的关注和帮助!

Try (assuming sufficient version of Python to preserve creation order of dict):尝试(假设 Python 有足够的版本来保留 dict 的创建顺序):

my_dict = {
    "name1": {"code1": {"brand1": 2}},
    "name2": {
        "code2.1": {"brand2.1": 2, "brand2.2": 8, "brand2.3": 5, "brand2.4": 4},
        "code2.2": {"brand2.1": 2, "brand1": 1, "brand2.5": 25},
    },
    "name3": {"code1": {"brand2.1": 2}, "code3": {"brand4": 1, "brand3.1": 2}},
}

out = {
    k: dict(sorted(v.items(), key=lambda d: sum(d[1].values()), reverse=True))
    for k, v in my_dict.items()
}
print(out)

Prints:印刷:

{
    "name1": {"code1": {"brand1": 2}},
    "name2": {
        "code2.2": {"brand2.1": 2, "brand1": 1, "brand2.5": 25},
        "code2.1": {"brand2.1": 2, "brand2.2": 8, "brand2.3": 5, "brand2.4": 4},
    },
    "name3": {"code3": {"brand4": 1, "brand3.1": 2}, "code1": {"brand2.1": 2}},
}

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

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