So, I read a lot of posts about recursive smoothing dictionaries in Python. No one (except one) came close to what I'm looking for. Firstly, a quick example of what I'm trying to accomplish:
An example of a dictionary with mixed entries: (keys and values will always be mixed types)
{'a': [{'b': {'c': 'd', 'e': 'f', 'g': 'h',
'i': {'j': {'k': ['l'], 'm': 'n'}},
'o': {'p': {'q': ['r', 's' ], 't': 'u'}}
}
}]
}
Required Conclusion:
{'a/b/c/d',
'a/b/e/f',
'a/b/g/h',
'a/b/i/j/k/l',
'a/b/i/j/m/n',
'a/b/o/p/q/r',
'a/b/o/p/q/s',
'a/b/o/p/t/u'}
The function should (theoretically) work with lists.
To explain a little what I'm doing, I'm trying to search through Mac plist, and other attempts to search by keyword or value were unsustainable at best. To compensate, I want to try a different approach. Convert the dictionary to a list of "paths" and then just find the paths.
I tried myself (and partially succeeded) and then found a better solution in the form of this:
def flatten(structure, key="", path="", flattened=None):
if flattened is None:
flattened = {}
if type(structure) not in(dict, list):
flattened[((path + "/") if path else "") + key] = structure
elif isinstance(structure, list):
for i, item in enumerate(structure):
flatten(item, "", "/".join(filter(None,[path,key])), flattened)
else:
for new_key, value in structure.items():
flatten(value, new_key, "/".join(filter(None,[path,key])), flattened)
return flattened
, . -, :
{'a/b/c' : 'd',
'a/b/e' : 'f',
'a/b/g' : 'h',
'a/b/i/j/k/': 'l',
'a/b/i/j/m' : 'n',
'a/b/o/p/q/': 's',
'a/b/o/p/t' : 'u'}
/. . -, , , script , . .
'a/b/o/p/q/': 's'
, , . Python, , , .
, , . , , , .
/.