Skip to content
Advertisement

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

I have a dict:

JavaScript

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':

JavaScript

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

JavaScript

does not work.

Advertisement

Answer

Try this instead:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement