PYTHON中字典的修改

PYTHON中字典的修改,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我是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]]} 现在

我是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_h2,后三个键名为AAA_h3。所以让我们让它变得更容易。我希望生成的词典如下所示:

  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 ! 

只需迭代字典并在另一个字典中收集类似的项,如下所示

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
返回与该键关联的对应值,我们将当前值附加到它上面。

这听起来像是一个需求陈述,而不是一个问题。得到了解决方案,得到了北眼的精彩回应!谢谢大家!!