Re: [問題] 找出dict中有相同value的key
※ 引述《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
推
12/20 15:16,
5年前
, 1F
12/20 15:16, 1F
推
12/20 15:19,
5年前
, 2F
12/20 15:19, 2F
→
12/20 15:21,
5年前
, 3F
12/20 15:21, 3F
推
12/20 17:38,
5年前
, 4F
12/20 17:38, 4F
推
12/24 20:48,
5年前
, 5F
12/24 20:48, 5F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 3 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章