Last active
February 15, 2020 01:42
-
-
Save ansvver/76a24038c9ab7b4cec835b3276e44075 to your computer and use it in GitHub Desktop.
trans normal dict to MongoDB dot natation format dict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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