我有一个列表和一本字典。我必须检查并打印两个容器中都存在的那些值。我正在尝试以下代码:

I have a list and a dictionary. I have to check and print those values who is present in both containers. I am trying below code:

dict = {1: {'host': 'vm224', 'vmImag': '182356_HFS', 'Img_type': 'User'},
    2: {'host': 'vm768', 'vmImag': '182356_HFS', 'Img_type': 'User'}
   3: {'host': 'vm333', 'vmImag': '182356_HFS', 'Img_type': 'User'}}   
list1 =['vm224', 'vm768'] 
for i in list1:
   for key in dict.keys():
      if dict[key]['host'] in list1:
      print(hosts

预期输出:应该是 'vm224'、'vm768'。因为这 2 个主机与 list1 和 dict 匹配。

我想确认一下我写的对不对。 谢谢

为了简化您的代码,首先使用字典中的所有可用主机创建 set。然后用这个集合过滤list1

dct = {
    1: {"host": "vm224", "vmImag": "182356_HFS", "Img_type": "User"},
    2: {"host": "vm768", "vmImag": "182356_HFS", "Img_type": "User"},
    3: {"host": "vm333", "vmImag": "182356_HFS", "Img_type": "User"},
}

list1 = ["vm224", "vm768"]

all_hosts = {d["host"] for d in dct.values()}

filtered_list = [v for v in list1 if v in all_hosts]
print(filtered_list)

打印:

['vm224', 'vm768']