作者vanilla1474 (wawa)
看板Python
标题[问题] 巢状字典的问题
时间Sat Oct 1 02:18:07 2016
大家好,我是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://webptt.com/cn.aspx?n=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
1F:推 Yshuan: 你画成树状图来看 试着对树做traversal 10/01 03:28
2F:推 lc85301: I got an Apple... (误 10/01 11:14
3F:推 IMPOSSIBLEr: you need to know the outer key in order to get 10/01 13:11
4F:→ IMPOSSIBLEr: the inner dict. And from your first case, you a 10/01 13:11
5F:→ IMPOSSIBLEr: re trying to get the keys from given value whic 10/01 13:11
6F:→ IMPOSSIBLEr: h is not what a dict can do. You need to write 10/01 13:11
7F:→ IMPOSSIBLEr: a class which extends dict and implement this s 10/01 13:11
8F:→ IMPOSSIBLEr: pecial method. 10/01 13:11
9F:推 s06yji3: 做另一个dict用价钱当key,value用list纪录商品 10/01 19:46
10F:推 longlongint: 改用sql吧 10/04 12:12
11F:推 BigBank: 可用for xx in dict.items() 去找 xx[0]是keys xx[1]是值 10/06 03:11
12F:→ BigBank: 详细做法可参考下篇 不过使用.items()是最简单的方法了 10/06 03:11