Skip to content
Advertisement

How to split a dictionary based on similarity of values into two separate dictionaries

I have a dict:

dictionary =  {'1': 'a',
     '2': 'a',
     '3': 'b',
     '4': 'b'}

and I want to split it such that one dict contains all items with value == 'a' and the other one all items with value == 'b':

dict_a = {'1': 'a',
     '2': 'a'}

dict_b = {'3': 'b',
     '4': 'b'}

How can I do this in an short way? My approach

dict_a = {}
dict_b = {}
for key, value in dictionary.items():
     if value == 'a':
         dict_a = dict(key, value)
     else:
         dict_b = dict(key, value)

does not work.

Advertisement

Answer

Try this instead:

dict_a={}
dict_b={}
for key, value in dictionary.items():
    if value == 'a':
        dict_a[key] = value
    else:
        dict_b[key] = value

In your original code, you were recreating dict_a or dict_b every time you went through the loop.

If you’re not absolutely sure that your starting dict contains ONLY "a" or "b" values, use this instead:

dict_a={}
dict_b={}
for key, value in dictionary.items():
    if value == 'a':
        dict_a[key] = value
    elif value == 'b':
        dict_b[key] = value
    else:
        pass
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement