PYTHON中字典的修改

2024-04-23 17:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者。我有下面这本词典,我想修改它以得到我需要的词典。它看起来是有线的,但你可以观察到钥匙几乎是相似的。你知道吗

 My_dict= {'AAA_h2_qqq11':[[1,3]],'AAA_h2_ppp13':[[2,3],[2,5],[2,7]],'AAA_h2_rrr12':[[3,4],[3,7]],'AAA_h3_qqq11':[[6,7]],'AAA_h3_ppp13':[[9,3],[9,8],[9,5]],'AAA_h3_rrr12':[[4,5],[4,7]]}

现在我想组合具有相同“h”部分的类似键的“值(在上面的dict中是列表)”。这样地。注意前三个键。它们有相同的“h2”部分。最后三个键有相同的“h3”部分。所以我想把这三个相似键的值组合起来,并把它放在一个大列表中,其中前三个键名为AAA\uh2,后三个键名为AAA\uh3。所以让我们更容易。我想要得到的词典如下:

  New_dict={ 'AAA_h2':[ [[1,3]], [[2,3],[2,5],[2,7]], [[3,4],[3,7]] ], 'AAA_h3': [ [[6,7]], [[9,3],[9,8],[9,5]], [[4,5],[4,7]] ] }

  I just want above dict but if you guys move one step forward and can do following format of same dictionary then it would be so fantastic. Just remove all those extra square brackets.   

   New_dict={ 'AAA_h2':[ [1,3],[2,3],[2,5],[2,7],[3,4],[3,7] ], 'AAA_h3': [ [6,7],[9,3],[9,8],[9,5],[4,5],[4,7] ] }

 You can use REGEX also to compare keys and then put values in list. I am okay with REGEX as well. I am familiar to it. I will greatly appreciate your help on this. Thanks ! 

Tags: and列表newith2candicth3
1条回答
网友
1楼 · 发布于 2024-04-23 17:44:31

只需遍历字典并在另一个字典中收集相似的项,如下所示

result = {}
for key, value in my_dict.iteritems():
    result.setdefault(key[:key.rindex("_")], []).append(value)
print result

输出

{'AAA_h2': [[[2, 3], [2, 5], [2, 7]], [[3, 4], [3, 7]], [[1, 3]]],
 'AAA_h3': [[[9, 3], [9, 8], [9, 5]], [[4, 5], [4, 7]], [[6, 7]]]}

这里,key[:key.rindex("_")]获取字符串,直到字符串中的最后一个_。因此,我们取这个字符串并设置一个新的列表作为对应的值,只有在字典中已经不存在键的情况下,,并且由于setdefault返回与键相关的对应值,所以我们将当前值附加到它。你知道吗

相关问题 更多 >