I have a nested dictionary like this:
{108: {Wallmart: {'ca': {'good': 'busy'}}}, 204: {Wallmart: {'ny': {'good': 'busy'}}}, 205: {Wallmart: {'ny': {'great': 'busy'}}}, 110: {CVS: {'ny': {'great': 'busy'}}}, 184: {Wallmart: {'fl': {'great': 'busy'}}}, 185: {Wallmart: {'fl': {'bad': 'busy'}}}, 105: {Wallmart: {'ga': {'bad': 'busy'}}}, 497: {Wallmart: {'ga': {'bad': 'busy'}}}, 400: {RiteAid: {'dc': {'good': 'busy'}}}, 406: {RidaAid: {'dc': {'geat': 'busy'}}}, 367: {Other: {'tx': {'bad': 'busy'}}}}
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:
204: {Wallmart: {'ny': {'good': 'busy'}}}, 205: {Wallmart: {'ny': {'great': 'busy'}}}, 110: {CVS: {'ny': {'great': 'busy'}}},
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:
{id: {name: {state: {level: status}}}, ...}
It would be easier to work with a structure like:
{state1: {id: {store_dict}, ...}, state2: {...}, ...}
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:
from collections import defaultdict states =defaultdict(list) for _id, store in data.items(): name = list(store.keys())[0] state = list(store[name].keys())[0] states[state][_id] = store
And now you can simply access states
with the state you want. So this is an example printing function:
def print_state(state): for _id, store in states[state].items(): print(_id, store, sep=': ')
And use it:
>>> print_state('ny') 204: {'Wallmart': {'ny': {'good': 'busy'}}} 205: {'Wallmart': {'ny': {'great': 'busy'}}} 110: {'CVS': {'ny': {'great': 'busy'}}}