Skip to content

Instantly share code, notes, and snippets.

@catichenor
Last active August 6, 2018 20:08
Show Gist options
  • Save catichenor/86d528511b4e88f51a57bff1405f95ee to your computer and use it in GitHub Desktop.
Save catichenor/86d528511b4e88f51a57bff1405f95ee to your computer and use it in GitHub Desktop.
Collect dictionary paths and values
test_info = {
'old_macs': {
'processors': [
{'68000': [
{'name': 'Mac 128k', 'color': False},
{'name': 'Mac 512k', 'color': False},
{'name': 'Mac Plus', 'color': False},
{'name': 'Mac SE', 'color': False},
]},
{'68020': [
{'name': 'Mac II', 'color': True},
]},
{'68030': [
{'name': 'Mac SE/30', 'color': False},
{'name': 'Mac IIci', 'color': True},
{'name': 'Mac IIfx', 'color': True},
]}
]}
}
path_dict = {}
def collect_dict_paths(nested, path_string):
this_path = path_string
if type(nested) == dict:
for k, v in enumerate(nested.items()):
if k != 0:
this_path = ':'.join(this_path.split(':')[0:-1])
this_path = ':'.join((this_path, v[0]))
if not this_path in path_dict:
path_dict[this_path] = set()
# print(v[0], this_path)
collect_dict_paths(v[1], this_path)
elif type(nested) == list:
for i in nested:
collect_dict_paths(i, this_path)
else:
if type(nested) == bool:
path_dict[this_path].add(True)
path_dict[this_path].add(False)
else:
path_dict[this_path].add(nested)
# print(nested)
collect_dict_paths(test_info, '')
print(path_dict)
for k, v in path_dict.items():
if v:
print(k, v)
# Outputs the following:
# {':old_macs': set(), ':old_macs:processors': set(), ':old_macs:processors:68000': set(), ':old_macs:processors:68000:name': {'Mac SE', 'Mac 512k', 'Mac Plus', 'Mac 128k'}, ':old_macs:processors:68000:color': {False, True}, ':old_macs:processors:68020': set(), ':old_macs:processors:68020:name': {'Mac II'}, ':old_macs:processors:68020:color': {False, True}, ':old_macs:processors:68030': set(), ':old_macs:processors:68030:name': {'Mac IIci', 'Mac SE/30', 'Mac IIfx'}, ':old_macs:processors:68030:color': {False, True}}
# :old_macs:processors:68000:name {'Mac SE', 'Mac 512k', 'Mac Plus', 'Mac 128k'}
# :old_macs:processors:68000:color {False, True}
# :old_macs:processors:68020:name {'Mac II'}
# :old_macs:processors:68020:color {False, True}
# :old_macs:processors:68030:name {'Mac IIci', 'Mac SE/30', 'Mac IIfx'}
# :old_macs:processors:68030:color {False, True}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment