Home > Mobile >  Best way to split a dict based on key
Best way to split a dict based on key

Time:09-27

I have a dict that looks like this (shortened)

{'18/09/2022-morning': [5.4, 6.0, 6.5, 6.7, 6.9, 7.9, 8.5, 7.5, 7.9, 7.8, 7.6, 6.8],
 '18/09/2022-night': [6.4, 5.7, 4.8, 5.4, 4.7, 4.3],
 '19/09/2022-morning': [3.8],
 '19/09/2022-night': [4.1, 4.4, 4.3, 3.8, 3.5, 2.8]}

What is the best way to split it into two different dictionaries based on morning/night? I can't think of an easy way to this! Example of desired output:

dic1 = {'18/09/2022-morning': [5.4, 6.0, 6.5, 6.7, 6.9, 7.9, 8.5, 7.5, 7.9, 7.8, 7.6, 6.8], '19/09/2022-morning': [3.8]}
dic2 = {'18/09/2022-night': [6.4, 5.7, 4.8, 5.4, 4.7, 4.3],  '19/09/2022-night': [4.1, 4.4, 4.3, 3.8, 3.5, 2.8]}

CodePudding user response:

mornings = {}
nights = {}

for k, v in d.items():
    if k.endswith("morning"):
        mornings[k] = v
    else:
        nights[k] = v

CodePudding user response:

You can split base '-' then base morning or night insert to desired dict.

dct = {'18/09/2022-morning': [5.4, 6.0, 6.5, 6.7, 6.9, 7.9, 8.5, 7.5, 7.9, 7.8, 7.6, 6.8],
       '18/09/2022-night': [6.4, 5.7, 4.8, 5.4, 4.7, 4.3],
       '19/09/2022-morning': [3.8],
       '19/09/2022-night': [4.1, 4.4, 4.3, 3.8, 3.5, 2.8]}


dic1, dic2 = {}, {}
for key, val in dct.items():
    if key.split('-')[1] == 'morning':
        dic1[key] = val
    else:
        dic2[key] = val

print(dic1)
print(dic2)

Output:

{'18/09/2022-morning': [5.4, 6.0, 6.5, 6.7, 6.9, 7.9, 8.5, 7.5, 7.9, 7.8, 7.6, 6.8], '19/09/2022-morning': [3.8]}

{'18/09/2022-night': [6.4, 5.7, 4.8, 5.4, 4.7, 4.3], '19/09/2022-night': [4.1, 4.4, 4.3, 3.8, 3.5, 2.8]}
  • Related