首页 > 解决方案 > 从具有多个值的字典中获取单个键的值的键

问题描述

给定一本字典

collision_domain  = {0: [0, 1, 2], 1: [2, 3, 4]}

此代码应输出domain 0

search = 1
for dom, node in collision_domain.items():
    if node == search:
        print("domain", dom)

我们如何得到它?

标签: pythondictionary

解决方案


我们在这里需要做的是在循环的每次迭代中在列表中进行搜索。

请注意,搜索值首先出现,然后是列表。 if search in node:

最终代码:

for dom, node in collision_domain.items():
    if search in node:
        print("domain", dom)

推荐阅读