pythonic way to collect specific data from complex dict
i need to collect some data from complext dict based on Dot Notation key names
for example
sample data
data = {
'name': {'last': 'smith', 'first': 'bob'},
'address':{'city': 'NY', 'state': 'NY'}开发者_Python百科,
'contact':{'phone':{'self':'1234', 'home':'222'}},
'age':38,
'other':'etc'
}
keys = ['contact.phone.self', 'name.last', 'age']
my logic
result = []
for rev_key in rev_keys:
current = data.copy()
rev_key = rev_key.split('.')
while rev_key:
value = rev_key.pop(0)
current = current[value]
result.append(current)
Thanks in advance!
[reduce(dict.get, key.split("."), data) for key in keys]
How about this?
def fetch( some_dict, key_iter ):
for key in key_iter:
subdict= some_dict
for field in key.split('.'):
subdict = subdict[field]
yield subdict
a_dict = {
'name': {'last': 'smith', 'first': 'bob'},
'address':{'city': 'NY', 'state': 'NY'},
'contact':{'phone':{'self':'1234', 'home':'222'}},
'age':38,
'other':'etc'
}
keys = ['contact.phone.self', 'name.last', 'age']
result = list( fetch( a_dict, keys ) )
Here's my crack at it:
>>> def find(tree,cur):
if len(cur)==1:
return tree[cur[0]]
else:
return find(tree[cur[0]],cur[1:])
>>> print [find(data,k.split(".")) for k in keys]
['1234', 'smith', 38]
Of course this will cause stack overflows if the items are too deeply nested (unless you explicitly raise the recursion depth), and I would use a deque
instead of a list
if this were production code.
Just write a function that gets one key at a time
def getdottedkey(data, dottedkey):
for key in dottedkey.split('.'):
data = data[key]
return data
print [getdottedkey(data, k) for k in keys]
精彩评论