简体   繁体   English

将python字典“键值”转换为具有“ k(value)ey”的字典

[英]Convert python dict “key value” into dict having “k(value) ey”

I have a dict 我有一个命令

d = {'A1BB11': 10,  
     'B1CC55': 20,  
     'A1A11':  30,  
     'A1A21':  40,  
     'B1HH21': 50,  
     'C1KK88': 60
    }

I want to get a new dict from prev dict d 我想从上一个字典中得到一个新的字典

new_d = {'A1(80)':['BB11', 'A11', 'A21'],  
         'B1(70)':['CC55', 'HH21'],  
         'C1(60)':['KK88']  
        }

Could you provide a simple pythonic way to it? 您能提供一种简单的pythonic方法吗? I am new to python world. 我是python世界的新手。

I think the simplest way would be to create two dictionaries to track the two values you're concerned with: the sums and the lists of suffixes. 我认为最简单的方法是创建两个字典来跟踪您所关注的两个值:和和后缀列表。

from collections import defaultdict

d1, d2 = defaultdict(int), defaultdict(list)

d = {'A1BB11': 10,  
     'B1CC55': 20,  
     'A1A11':  30,  
     'A1A21':  40,  
     'B1HH21': 50,  
     'C1KK88': 60
    }

for k, v in d.items():
    prefix = k[:2]
    d1[prefix] += v
    d2[prefix].append(k[2:])

final = {'{}({})'.format(k, d1[k]): v for k, v in d2.items()}

print(final)
# {'A1(80)': ['BB11', 'A11', 'A21'],
#  'B1(70)': ['CC55', 'HH21'],
#  'C1(60)': ['KK88']}

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

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