Re: [問題] 巢狀字典的問題

看板Python作者 (I'm possible rrr)時間7年前 (2016/10/01 13:33), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/3 (看更多)
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 啊...... -- ⒾⓂⓅⓄⓈⓈⒾⒷⓁⒺⓡ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 67.161.6.82 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1475299981.A.ED8.html

10/08 14:06, , 1F
thank you for this thorough demostration
10/08 14:06, 1F
文章代碼(AID): #1NxqgDxO (Python)
文章代碼(AID): #1NxqgDxO (Python)