[問題] 巢狀字典的問題

作者: vanilla1474 (wawa)   2016-10-01 02:18:07
大家好,我是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 啊......
感激不盡了!
作者: Yshuan (倚絃)   2016-10-01 03:28:00
你畫成樹狀圖來看 試著對樹做traversal
作者: lc85301 (pomelocandy)   2016-10-01 11:14:00
I got an Apple... (誤
作者: IMPOSSIBLEr (I'm possible rrr)   2016-10-01 13:11:00
you need to know the outer key in order to getthe inner dict. And from your first case, you are trying to get the keys from given value which is not what a dict can do. You need to writea class which extends dict and implement this special method.
作者: s06yji3 (阿南)   2016-10-01 19:46:00
做另一個dict用價錢當key,value用list紀錄商品
作者: longlongint (華哥爾)   2016-10-04 12:12:00
改用sql吧
作者: BigBank ( )   2016-10-06 03:11:00
可用for xx in dict.items() 去找 xx[0]是keys xx[1]是值詳細做法可參考下篇 不過使用.items()是最簡單的方法了

Links booklink

Contact Us: admin [ a t ] ucptt.com