問題描述
給定 n 個字典,編寫一個函數,該函數將返回一個唯一字典,其中包含重復鍵的值列表.
Given n dictionaries, write a function that will return a unique dictionary with a list of values for duplicate keys.
例子:
結果:
到目前為止我的代碼:
生成一個為這些重復鍵生成一個值列表的新字典的最佳方法是什么?
What would be the best way to produce a new dictionary that yields a list of values for those duplicate keys?
推薦答案
這會返回:
這個問題略有不同.這里所有的字典值都是列表.如果長度為 1 的列表不希望這樣做,則添加:
There is a slight difference to the question. Here all dictionary values are lists. If that is not to be desired for lists of length 1, then add:
在 return d
語句之前.但是,我真的無法想象您何時想要刪除該列表.(考慮將列表作為值的情況;然后刪除項目周圍的列表會導致模棱兩可的情況.)
before the return d
statement. However, I cannot really imagine when you would want to remove the list. (Consider the situation where you have lists as values; then removing the list around the items leads to ambiguous situations.)
這篇關于合并字典,保留重復鍵的值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!