Skip to main content
 首页 » 编程设计

python之按键名合并字典值

2025年05月04日14zhengyun_ustc

我有一个列表字典,其中包含名称非常相似的键,我需要将它们合并在一起;例如,

new_dict = { 
    'a0':['hello', 'how'], 
    'a1':['are'], 
    'a2':['you'], 
    'b0':['fine'], 
    'b1':['thanks'] 
} 

我想要这样的东西:

desired = { 
    'a':['hello', 'how', 'are', 'you'], 
    'b':['fine', 'thanks'] 
} 

虽然我可以像这样更改键,就好像它是一个列表元素一样:

for key in new_dict.keys(): 
    if 'a' in key: 
        key == 'a' 

但这显然行不通。最好的方法是什么?谢谢。

请您参考如下方法:

这是一种方式:

from collections import defaultdict 
d = defaultdict(list) 
 
for k, v in new_dict.items(): 
    d[k[0]].extend(v) 
 
# defaultdict(list, 
#             {'a': ['hello', 'how', 'are', 'you'], 'b': ['fine', 'thanks']})