Python:验证查找字典与列表中共同Host值的代码正确性
Your Code Issues and Corrected Version
First, let's break down the problems in your original code that prevent it from working as expected:
- Syntax Error: Your dictionary is missing a comma between the second and third entries. This will immediately throw a syntax error when Python tries to parse the code.
- Bad Variable Name: Using
dictas a variable name overrides Python's built-indicttype, which is poor practice and can cause unexpected behavior later. - Undefined Variable: You try to print
hosts, but this variable is never defined in your code. You need to reference the actual host value from the dictionary entry instead. - Redundant & Inefficient Loops: The nested loops will print matching hosts multiple times (once for each item in
list1), and checking membership in a list inside a loop is slower than using a set for lookups.
Here's a corrected version that fixes all these issues and produces your expected output:
# Rename dict to vm_dict to avoid overriding the built-in type vm_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'] # Convert list1 to a set for faster membership checks target_hosts = set(list1) # Iterate through each VM entry in the dictionary for vm_entry in vm_dict.values(): current_host = vm_entry['host'] if current_host in target_hosts: print(current_host)
Why This Works:
- Fixed Syntax: The dictionary now has proper commas between entries, so Python can parse it correctly.
- Clear Variable Name:
vm_dictdescribes the content of the dictionary and avoids conflicting with built-in types. - Defined Target Variable: We extract
current_hostfrom each dictionary entry and print it directly when it matches our target list. - Efficient Lookups: Using a set (
target_hosts) makes checking if a host exists inlist1much faster (especially useful if your list grows larger). - No Duplicates: This code prints each matching host exactly once, even if multiple dictionary entries share the same host.
If you want to print the hosts in the exact order they appear in list1, use this alternative approach:
vm_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'] # Collect all hosts from the dictionary into a set dict_hosts = {entry['host'] for entry in vm_dict.values()} # Loop through list1 and print hosts that exist in the dictionary for host in list1: if host in dict_hosts: print(host)
This will output vm224 followed by vm768, exactly as you expected.
内容的提问来源于stack exchange,提问作者sonal
相关产品推荐
相关产品推荐

