How can I split a dictionary in several dictionaries based on a part of values using Python

I think this is what you want to do, in a sense. The result is one main ('mother') dictionary that has as keys all possible first letters, and as values the corresponding dicts.

from collections import defaultdict
d = {'sku1': 'k-1','sku2': 'k-2','sku3': 'b-10' ,'sku4': 'b-1', 'sku5': 'x-1', 'sku6':'x-2'}

mother = defaultdict(dict)
for key, val in d.items():
    mother[val[0]][key] = val

mother = dict(mother)
print(mother)

Output:

{'k': {'sku1': 'k-1', 'sku2': 'k-2'},
 'b': {'sku3': 'b-10', 'sku4': 'b-1'},
 'x': {'sku5': 'x-1', 'sku6': 'x-2'}}

You can then make them easily accessible like so.

k_dict = mother['k']
b_dict = mother['b']
x_dict = mother['x']

If you want more control and want to be able to give the size of key, we can do it like so:

from collections import defaultdict


def split_d(d, key_size=1):
    if key_size < 1:
        raise ValueError("'key_size' must be 1 or more")

    mother = defaultdict(dict)
    for key, val in d.items():
        mother[val[0:key_size]][key] = val

    return dict(mother)

if __name__ == '__main__':
    d = {'sku1': 'k-1','sku2': 'k-2','sku3': 'b-10' ,'sku4': 'b-1', 'sku5': 'x-1', 'sku6':'x-2'}

    res = split_d(d, 3)
    print(res)

Tags:

Python