[英]How to get a particular key value pair from a dict in Python
I have a dict like below我有一个像下面这样的字典
d = {"a":0,"b":1,"c":2}
I need to get only this in my output dict我只需要在我的输出字典中得到这个
out = {"b":1}
tried converting the dict to list and accessing the index 1, but it gives me tuples.尝试将字典转换为列表并访问索引 1,但它给了我元组。 Is there any workaround for this
有什么解决方法吗
print(list(d.items())[1])
("b",1)
你可以做out = {elem:d[elem] for idx,elem in enumerate(d) if idx in [0,1]}
来选择[0,1]
但dict([list(d.items())[1]])
,正如@Anetropic 所提到的,也可以正常工作。
What is the source of your key value?你的关键值的来源是什么? If you want to get all the items in dictionary from a key container:
如果要从密钥容器中获取字典中的所有项目:
>>> keys = ['b', 'c']
>>> {key: d[key] for key in keys}
{'b': 1, 'c': 2}
If you just want to get it in order from d.items()
:如果您只想从
d.items()
中按顺序获取它:
>>> from itertools import islice
>>> dict(islice(d.items(), 1, 3))
{'b': 1, 'c': 2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.