作者Hsins (迅雷不及掩耳盜鈴)
看板Python
標題Re: [問題] 找出dict中有相同value的key
時間Fri Dec 20 14:49:21 2019
※ 引述《renshin (阿信)》之銘言:
: 請問要如何用dict中的value找key呢?
: 例如有個dict
: d = {'a':'100', 'b':'200', 'c':'200', 'd':'100', 'e':'150'}
: 想把帶有相同value的key集合起來成各自一個list
: 或者可能形成一個新的dict,如
: Newd = {'100':['a','d'], '150':'e', '200':['b','c']}
: 請問有大大可以教一下新手小嫩嗎?
: 謝謝
用 for 去遍歷 dict 中的 key 跟 value 就可以了
```python
# declare the result dict to store reversed dict
result = {}
# traverse original dict
d = {'a': '100', 'b': '200', 'c': '200', 'd': '100', 'e': '150'}
for k, v in d.items():
result.setdefault(v, list()).append(k)
```
---
順帶一提,這邊用的 setdefault() 跟我寫的這篇
#1T-Uj77Q (Python)
用到的 defaultdict 是還滿異曲同工的東西
可以讓你的代碼寫起來更加地 pythonic 一點
不過建議使用 defaultdict 會更好一些
> It would make sense that defaultdict is faster that dict.setdefault()
> since the former sets its default for the entire dict at creation time,
> whereas setdefault() does it per element when it is read. One reason to
> use setdefault is when the default you assign is based on the key (or
> something) rather than a generic default for the entire dict.
# References
提升逼格的两个函数:setdefault 与 defaultdict
https://bit.ly/2Mtgj7N
setdefault vs defaultdict performance
https://bit.ly/2Md9Ayw
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.247.1 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1576824563.A.55A.html
※ 編輯: Hsins (140.112.247.1 臺灣), 12/20/2019 14:56:15
推 renshin: 感謝大大教學!! 12/20 15:16
推 renshin: 但我原data就是dict,似乎無法用defaultdict?? 12/20 15:19
→ Hsins: defaultdict 沒有用在你原來的 dict 12/20 15:21
推 cuteSquirrel: 推 12/20 17:38
推 onegoman: 推。 12/24 20:48