Home > Back-end >  Splitting dictionary depending on key name
Splitting dictionary depending on key name

Time:11-26

I have a dictionary that I need to split up into smaller dictionaries depending on the key name using the values from an array:

dict = {'1_100': 50, '1_102': 100, '2_100': 150, '2_102': 200, '3_100': 50, '3_102': 100, ...}

narray = [1, 2, 3, 4, 5, ...]

I am trying to split up the dictionary depending on the first number of the key

So far I have done the following:

for k, v in dict.items():
    for t in narray:
        if str(t)   "_" in str(dict.keys()):

             

I am unsure how to do the actual splitting part and ensuring that a new dictionary is made when it comes across new number in the "X_" key. Note there are a different number of each keys, so splitting every nth number would not work

I want to ideally end up with

dict1 = {'1_100': 50, '1_102': 100, ...}
dict2 = {'2_100': 50, '2_102': 100, ...}
dict3 = {'3_100': 50, '3_102': 100, ...}
dictN = {'N_100': 50, 'N_102': 100, ...}

Any help would be greatly appreciated

CodePudding user response:

data = {'1_100': 50, '1_102': 100, '2_100': 150, '2_102': 200, '3_100': 50, '3_102': 100}

for k,v in data.items():
    name = "dict"   k.split("_")[0]
    d = globals().get(name, {})
    d.update({k:v})
    globals()[name] = d

print(dict1)
print(dict2)
print(dict3)

Result:

{'1_100': 50, '1_102': 100}

{'2_100': 150, '2_102': 200}

{'3_100': 50, '3_102': 100}

CodePudding user response:

Try this:

dcts = {str(n): {} for n in narray}
for k, v in dct.items():
    dcts[k.split('_')[0]][k] = v
dcts = list(dcts.values())

dct is your initial dictionary, dcts is a list of dictionaries (you may want to remove the empty ones).

  • Related