Search code examples
pythonlistdictionarynested

Creating a dictionary from a subset of a list


Suppose I have python list like this:

master_list = ['a_1', 'b_4', 'd_2', 'c_3', 
              'a_2', 'c_1', 'd_4', 'b_3', 
              'd_3', 'c_2', 'a_4', 'b_1', 
              'c_4', 'a_3', 'b_1', 'd_1']

Each item in the list is a letter, underscore, and number. I want a dictionary to group this items by number in a list like this:

 my_dict = {'1': [], '2': [], '3': [], '4':[]}

While I could use the following to populated my lists inside my_dict, it seems awkward. Is there a more efficient way to achieve this?

for item in master_list:
    if '_1' in item:
        my_dict['1'].append(item)
    elif '_2' in item:
        my_dict['2'].append(item)
    elif '_3' in item:
        my_dict['3'].append(item)
    elif '_4' in item:
        my_dict['4'].append(item)

Solution

  • You can use the builtin split function to split the input items on _ character.

    sortd_dict = {}
    def add_in_dict(k, v):
        if k not in d:
            sortd_dict[k] = [v]
        else:
            sortd_dict[k].append(v)
    
    for item in master_list:
        add_in_dict(item.split("_")[-1], item)