Re: [问题] 巢状字典的问题

楼主: IMPOSSIBLEr (I'm possible rrr)   2016-10-01 13:32:56
For a dict, you must know the key in order to get the values.
There is no built-in method to get what you need like
"given a value, return all the keys"
this is just not what a dict was designed to do.
Here is a quick generator that traverse through the entire dict just like
it was a forest (multiple trees).
def traverse_dict(obj):
"""
A dict is actually a forest which contains multiple trees, so instead
of recursion, we can also simply use multiple level-order traversal
to traverse the entire dict iteratively
@param obj: A dict
@type obj: dict
@return: A generator that traverse the entire dict and return
(key, value, parent_keys=[])
"""
if not isinstance(obj, dict):
raise ValueError('Given obj must be of type dict')
queue = deque()
for k, v in obj.items():
# put current level, highest level, no parent_keys
queue.append((k, v, []))
while queue:
k, v, parent_keys = queue.popleft()
if not isinstance(v, dict):
yield (k, v, parent_keys)
else:
for k1, v1 in v.items():
queue.append((k1, v1, parent_keys + [k]))
And if you really need to access the inner dict directly.
def set_flat_item(obj, flat_key, value, delimiter='.'):
"""
Set dict item using flat_key
@param obj: A dict to setitem
@param flat_key: delimiter delimited string to indicate multi level
@param delimiter: delimiter
"""
keys = str(flat_key).split(delimiter)
current = obj
for key in keys[:-1]:
if key not in current:
current[key] = {}
current = current[key]
current[keys[-1]] = value
For you first case, you need to find all the keys where their value is 30
then using traverse_dict()
ret = []
for k, v, parent_keys in traverse_dict(A):
if v == 30:
ret.append(k)
return ret
Hope this helps.
※ 引述《vanilla1474 (wawa)》之铭言:
: 大家好,我是Python 超级新手,最近自学遇到dict问题,卡关好多天了,麻烦大家教教
: 我了。
: A = { 'fruits': { 'apple': 10, 'bananas': 30, 'orange': 22 }, 'meat': { 'beef'
: : 50, 'pork': 45, 'chicken':30 } }
: 当我输入30时,如何得到对应的key: bananas & chicken 的答案?反过来,如果是知道A
: pple 怎么得到它的value呢?
: 我只会从最外面一层一层进去查
: 例:A['meat']['beef'] = 50
: 一直想不出可以用什么方法找出内层字典的 key & value 啊......
作者: sunnoset (skj)   2016-10-08 14:06:00
thank you for this thorough demostration

Links booklink

Contact Us: admin [ a t ] ucptt.com