首页 > 解决方案 > 在 python 中的字典键中添加了多个值。如何检索指定的值?

问题描述

以下代码源自此站点上的一个过去问题,在此处找到 --> How to add multiple values to a dictionary key in python? 此代码允许您为字典中的键分配多个值。我尝试了几种方法来使用该.get方法使用字典键返回指定的列表值,但到目前为止没有任何效果。如果这个问题之前已经被问过,请告诉我正确的线程。到目前为止,我还没有找到任何关于此的内容。任何帮助表示赞赏。

a = {}
a["abc"] = [1, 2, "bob"]

print(a.get("abc"))   # this prints [1, 2, 'bob']

print(a.get("abc"[1])) #this is an example of one of the things that I tried. Prints None

预期输出print(a.get("abc"[1]))

2

实际输出:

None

标签: pythondictionary

解决方案


您需要索引从get操作中获得的列表,如下所示:

a.get("abc")[1]

为什么a.get("abc"[1])没有任何意义?

a.get("abc"[1])a.get("b")


推荐阅读