Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def flatten_dictionary(dictionary):
- return flat(dictionary)
- def flat(dictionary):
- if len(dictionary) == 0:
- return {}
- results = {}
- for key, value in iter(dictionary.items()):
- if type(value) is dict:
- sub_dict = flat(value)
- for k, v in iter(sub_dict.items()):
- if len(key) == 0:
- results[k] = v
- elif len(k) == 0:
- results[key] = v
- else:
- results[key + "." + k] = v
- else:
- results[key] = value
- return results
- # each key i check if the value is string or integer
- # each nested value
- dictionary = {
- "Key1" : "1",
- "Key2" : {
- "a" : "2",
- "b" : "3",
- "c" : {
- "d" : "3",
- "e" : "1"
- }
- }
- }
- print(flatten_dictionary(dictionary))
Add Comment
Please, Sign In to add comment