作者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://webptt.com/cn.aspx?n=bbs/Python/M.1576824563.A.55A.html
※ 编辑: Hsins (140.112.247.1 台湾), 12/20/2019 14:56:15
1F:推 renshin: 感谢大大教学!! 12/20 15:16
2F:推 renshin: 但我原data就是dict,似乎无法用defaultdict?? 12/20 15:19
3F:→ Hsins: defaultdict 没有用在你原来的 dict 12/20 15:21
4F:推 cuteSquirrel: 推 12/20 17:38
5F:推 onegoman: 推。 12/24 20:48