[問題] 巢狀字典的問題

看板Python作者 (wawa)時間8年前發表 (2016/09/30 18:18), 8年前編輯推噓6(606)
留言12則, 6人參與, 最新討論串1/3 (看更多)
大家好,我是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), 來自: 123.193.170.223 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1475259490.A.F24.html ※ 編輯: vanilla1474 (123.193.170.223), 10/01/2016 02:18:52 ※ 編輯: vanilla1474 (123.193.170.223), 10/01/2016 02:19:19

10/01 03:28, , 1F
你畫成樹狀圖來看 試著對樹做traversal
10/01 03:28, 1F

10/01 11:14, , 2F
I got an Apple... (誤
10/01 11:14, 2F

10/01 13:11, , 3F
you need to know the outer key in order to get
10/01 13:11, 3F

10/01 13:11, , 4F
the inner dict. And from your first case, you a
10/01 13:11, 4F

10/01 13:11, , 5F
re trying to get the keys from given value whic
10/01 13:11, 5F

10/01 13:11, , 6F
h is not what a dict can do. You need to write
10/01 13:11, 6F

10/01 13:11, , 7F
a class which extends dict and implement this s
10/01 13:11, 7F

10/01 13:11, , 8F
pecial method.
10/01 13:11, 8F

10/01 19:46, , 9F
做另一個dict用價錢當key,value用list紀錄商品
10/01 19:46, 9F

10/04 12:12, , 10F
改用sql吧
10/04 12:12, 10F

10/06 03:11, , 11F
可用for xx in dict.items() 去找 xx[0]是keys xx[1]是值
10/06 03:11, 11F

10/06 03:11, , 12F
詳細做法可參考下篇 不過使用.items()是最簡單的方法了
10/06 03:11, 12F
文章代碼(AID): #1NxgnYya (Python)
文章代碼(AID): #1NxgnYya (Python)