Skip to content

Instantly share code, notes, and snippets.

@AnkDos
Created October 9, 2021 18:45
Show Gist options
  • Save AnkDos/42d141d6a1c3019307cbe1f782050bfd to your computer and use it in GitHub Desktop.
Save AnkDos/42d141d6a1c3019307cbe1f782050bfd to your computer and use it in GitHub Desktop.
Flatten a dictonary , nested dictionary into plain dictonary
def flatten(data):
flatten_dict = {}
def flat(data_, key, pkey=''):
if isinstance(data_, dict):
if data_ == dict():
flatten_dict[f"{pkey}"] = data_
for key, value in data_.items():
key_fmt = [pkey, key]
if pkey == '':
key_fmt = [key]
flat(value, key, '.'.join(key_fmt))
return data_
elif isinstance(data_, list):
if data_ == list():
flatten_dict[f"{pkey}"] = data_
temp = []
for i, item in enumerate(data_):
key_fmt = [pkey, str(i)]
if pkey == '':
key_fmt = [str(i)]
temp.append(flat(item, key, '.'.join(key_fmt)))
return temp
elif data_ is None:
return None
flatten_dict[f"{pkey}"] = data_
return data_
flat(data, '')
return flatten_dict
flatten({'hello': 'world', 'nice': ['here', {'car': 'masarati', 'mo': 'dl'}], 'gabagool': {'category': ['food'], 'taste': 'good'}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment