Created
April 9, 2014 17:11
-
-
Save adewes/10293117 to your computer and use it in GitHub Desktop.
Python: Dictionary Value Exporter
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
def export(d,key): | |
""" | |
Exports a set of values from a nested dict. | |
Example usage: | |
d = { | |
'name' : 'test', | |
'remote_servers' : | |
{ 'us' : | |
{'ip' : [111,201,32,1], | |
'password' : 'super_secret_pw'}, | |
'eu' : | |
{'ip' : [111,22,37,3], | |
'password' : 'super_secret_pw' | |
}, | |
} | |
} | |
#We only want to export the name and the ip of the remote servers, but not their passwords! | |
export(d,('name', {'remote_servers' : {'*' : ('ip',)} } )) | |
#Return value: | |
#{'name': 'test', 'remote_servers': {'eu': {'ip': [111, 22, 37, 3]}, 'us': {'ip': [111, 201, 32, 1]}}} | |
As usual, the '*' is a wildcard that matches all keys from a dict. | |
""" | |
ed = {} | |
if isinstance(key,tuple) or isinstance(key,list): | |
for key_params in key: | |
res = export(d,key_params) | |
ed.update(res) | |
elif isinstance(key,unicode) or isinstance(key,str): | |
if key == '*': | |
for d_key in d: | |
ed[d_key] = d[d_key] | |
else: | |
if key in d: | |
ed[key] = d[key] | |
elif isinstance(key,dict): | |
for key_name,key_value in key.items(): | |
if key_name == '*': | |
for d_key in d: | |
ed[d_key] = export(d[d_key],key_value) | |
else: | |
if key_name in d: | |
ed[key_name] = export(d[key_name],key_value) | |
return ed | |
if __name__ == '__main__': | |
d = { | |
'name' : 'test', | |
'remote_servers' : | |
{ 'us' : | |
{'ip' : [111,201,32,1], | |
'password' : 'super_secret_pw'}, | |
'eu' : | |
{'ip' : [111,22,37,3], | |
'password' : 'super_secret_pw' | |
}, | |
} | |
} | |
print export(d,('name', {'remote_servers' : {'*' : ('ip',)} } )) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment