Skip to content

Instantly share code, notes, and snippets.

@adewes
Created Apr 9, 2014
Embed
What would you like to do?
Python: Dictionary Value Exporter
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