如何在Python列表转字典的函数中筛选返回指定键值对?
Hey David, let's fix this up and make your function do exactly what you need!
First, let's clear up the error you ran into: you tried calling .items() on mylist, which is a list, not a dictionary. Lists don't have an .items() method—that's a dictionary feature. You need to first convert your list to a dictionary (like you did with dict(enumerate(items, 1))) before you can iterate over key-value pairs.
Step 1: Filter for odd keys
Let's modify your function to first create the full dictionary, then filter it to keep only the key-value pairs where the key is odd. We can use a dictionary comprehension for this—it's concise and efficient:
import string mylist = list(string.ascii_lowercase) def list_conversion(items): # Create the full dictionary with 1-based indexing full_dict = dict(enumerate(items, 1)) # Filter to keep only odd keys filtered_dict = {key: value for key, value in full_dict.items() if key % 2 != 0} print(filtered_dict) # Or return filtered_dict if you want to use the result later list_conversion(mylist)
This will output {1: 'a', 3: 'c', 5: 'e', ..., 25: 'y'}—exactly the odd-keyed pairs you wanted.
Step 2: Make it generic (filter any key/value condition)
If you want the function to handle any custom filter (not just odd keys), you can add a parameter that accepts a filter function. This makes your function reusable for all kinds of conditions:
import string mylist = list(string.ascii_lowercase) def list_conversion(items, filter_func=None): # Create the base dictionary full_dict = dict(enumerate(items, 1)) # If no filter is provided, return the full dictionary if filter_func is None: return full_dict # Apply the custom filter return {key: value for key, value in full_dict.items() if filter_func(key, value)} # Example 1: Filter for odd keys odd_key_filter = lambda key, value: key % 2 != 0 print(list_conversion(mylist, odd_key_filter)) # Example 2: Filter for vowels (values that are a, e, i, o, u) vowel_filter = lambda key, value: value in {'a', 'e', 'i', 'o', 'u'} print(list_conversion(mylist, vowel_filter)) # Example 3: Filter for keys greater than 20 large_key_filter = lambda key, value: key > 20 print(list_conversion(mylist, large_key_filter))
Why your original code failed
Just to recap: your error AttributeError: 'list' object has no attribute 'items' happened because you tried to loop over mylist.items(), but mylist is a list. You need to work with the dictionary you created from the list (the result of dict(enumerate(items, 1))) instead of the list itself.
This approach gives you flexibility—you can now filter for any condition you want by passing a custom lambda or function to list_conversion.
内容的提问来源于stack exchange,提问作者David

