Skip to content

Instantly share code, notes, and snippets.

@ansvver
Last active February 15, 2020 01:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ansvver/76a24038c9ab7b4cec835b3276e44075 to your computer and use it in GitHub Desktop.
Save ansvver/76a24038c9ab7b4cec835b3276e44075 to your computer and use it in GitHub Desktop.
trans normal dict to MongoDB dot natation format dict
#!/usr/bin/env python
# coding: utf-8
def dict2dot(foo, bar):
for k, v in foo.items():
if not isinstance(v, dict):
bar[k] = v
continue
for kk, vv in v.items():
dict2dot({'{}.{}'.format(k, kk): vv}, bar)
foo = {
'a0': 1,
'a1': {
'b0': 2,
'b1': 3,
'b2': {
'c0':4
},
'b3': 6,
'b4': {
'c0':7
}
},
'a2': 5
}
bar = {}
print foo
dict2dot(foo, bar)
print bar
"""
Output:
{'a1': {'b4': {'c0': 7}, 'b0': 2, 'b1': 3, 'b2': {'c0': 4}, 'b3': 6}, 'a0': 1, 'a2': 5}
{'a1.b4.c0': 7, 'a1.b3': 6, 'a1.b1': 3, 'a1.b0': 2, 'a1.b2.c0': 4, 'a0': 1, 'a2': 5}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment