Skip to content
Advertisement

matching on some values but not others in nested dict

I have a nested dictionary like this:

JavaScript

What I need to do is iterate over this data and find the keys with the same state but different shop names. For example, with the data provided above the output should end up with just:

JavaScript

Because the states (ny) match but the shop name (wallmart, cvs) do not match.

I’d then do a user_input asking to user of this code to specify if they want “Wallmart” or “CVS”. That part I’m fine with but pulling the information out of this dictionary is proving difficult

Advertisement

Answer

Your dict’s structure is:

JavaScript

It would be easier to work with a structure like:

JavaScript

For this conversion we need to get the state which is done by taking the only key in each level and using it to access the next. We will also use a defaultdict to dynamically create the list for each state:

JavaScript

And now you can simply access states with the state you want. So this is an example printing function:

JavaScript

And use it:

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