如何从嵌套字典中提取指定键的所有值?Python新手求助
Hey there! No worries at all—every Python beginner hits these kinds of snags, so don't feel bad about asking. Let's break down what's going wrong here, then fix it and look at some cleaner, more efficient ways to get the job done.
问题出在哪?
Your core issue is how you're referencing clientname in your final loop. Let's walk through it:
- When you built
clientlist, the variableclientnamewas updated each time through the loop, ending with the last value ('shanghai co.'). - Later, when you run this code:
You're not actually using thefor val in [x.values() for x in clientlist.values()]: matter_codes_only.append(clientlist[clientname].get('Matter Code'))valvariable from the loop—you just keep pulling theMatter Codefor the last client you processed (shanghai co.) twice (once for each entry in your CSV). That's why you get['3569', '3569']instead of the two distinct codes.
On top of that, the [x.values() for x in clientlist.values()] part is unnecessary—it creates a list of lists of values (like [['897', '0095', '...'], ['965', '3569', '...']]) but you don't use those values at all.
正确的基础写法
Let's fix the loop first. Since clientlist.values() gives you all the inner dictionaries directly, you can loop through those and pull the Matter Code from each:
matter_codes_only = [] for sub_dict in clientlist.values(): matter_codes_only.append(sub_dict['Matter Code'])
This will give you the expected ['0095', '3569'] (order might vary if you're using Python <3.7, since dicts didn't preserve insertion order before that). If you want to safely handle cases where Matter Code might be missing, use .get() with a default value:
matter_codes_only.append(sub_dict.get('Matter Code', None))
更高效的实现方法
For a more concise and Pythonic approach, use a list comprehension—it's shorter, faster, and easier to read once you get the hang of it:
matter_codes_only = [sub_dict['Matter Code'] for sub_dict in clientlist.values()]
If you're working with a huge dataset and don't need to store all the codes in memory at once, use a generator expression instead (swap the brackets for parentheses):
matter_codes_generator = (sub_dict['Matter Code'] for sub_dict in clientlist.values())
You can iterate over this generator one code at a time without loading everything into memory.
额外小提示
When building your clientlist, if you have multiple entries for the same clientname, your current code will overwrite the existing entry (since dicts can't have duplicate keys). If your CSV might have multiple matters per client, you might want to adjust the structure—like making each client's value a list of matter dictionaries instead of a single dict. But that's a separate problem for another day!
内容的提问来源于stack exchange,提问作者gcqhk19

