Put all elements in a dict form that have the same name

chi*_*tra 1 python regex

I have a list such as:

list=["Chrm_23-56_python_regius","Chrm_3-89_elephant_regius",
      "Chrm_13-56_monkey_regius","Chrm_13-34_rat_regius","Chrm_67-123_python_regius",
      "chrm_90-345_elephant_regius","Chrm_67-124_monkey_regius",
      "Chrm_345-456_rat_regius","Chrm_789-1000_python_regius"]
Run Code Online (Sandbox Code Playgroud)

and the idea is to put all element in a dict form that have the same name (without the number-number) part. and get something like:

dict = {'key1': ['Chrm_23-56_python_regius','Chrm_67-123_python_regius','Chrm_789-1000_python_regius'],
        'key2': ['Chrm_3-89_elephant_regius','chrm_90-345_elephant_regius'],
        'key3': ['Chrm_13-56_monkey_regius','Chrm_67-124_monkey_regius'],
        'key4': ['Chrm_13-34_rat_regius','Chrm_345-456_rat_regius']}
Run Code Online (Sandbox Code Playgroud)

As you can see for instance, in the key1, the 3 values (without the number-number) are = to Chrm__python_regius.

I know how to see which element is the same without the number-number part by doing:

for i in list:
    print(re.sub(r'[\d]+[-]+[\d]+', '',i)
Run Code Online (Sandbox Code Playgroud)

But I do not know how to create a dict and add in the same keys the values that have the same name structure. Does anyone have an idea?

Rak*_*esh 5

Using regex: --> re.sub(r"\d*\-\d*", "", i)

Ex:

import re
from collections import defaultdict
lst=["Chrm_23-56_python_regius","Chrm_3-89_elephant_regius","Chrm_13-56_monkey_regius","Chrm_13-34_rat_regius","Chrm_67-123_python_regius","chrm_90-345_elephant_regius","Chrm_67-124_monkey_regius","Chrm_345-456_rat_regius","Chrm_789-1000_python_regius"]

result = defaultdict(list)
for i in lst:
    result[re.sub(r"\d*\-\d*", "", i)].append(i)
print(result)
Run Code Online (Sandbox Code Playgroud)

Output:

defaultdict(<type 'list'>, {'Chrm__elephant_regius': ['Chrm_3-89_elephant_regius'], 'Chrm__python_regius': ['Chrm_23-56_python_regius', 'Chrm_67-123_python_regius', 'Chrm_789-1000_python_regius'], 'Chrm__monkey_regius': ['Chrm_13-56_monkey_regius', 'Chrm_67-124_monkey_regius'], 'Chrm__rat_regius': ['Chrm_13-34_rat_regius', 'Chrm_345-456_rat_regius'], 'chrm__elephant_regius': ['chrm_90-345_elephant_regius']})
Run Code Online (Sandbox Code Playgroud)