aks*_*hat 3 python dictionary append defaultdict dictionary-comprehension
我有一个字典(数据)列表,并希望将其转换为字典(x),如下所示。我正在使用以下“for循环”来实现。
data = [{'Dept': '0123', 'Name': 'Tom'},
{'Dept': '0123', 'Name': 'Cheryl'},
{'Dept': '0123', 'Name': 'Raj'},
{'Dept': '0999', 'Name': 'Tina'}]
x = {}
for i in data:
if i['Dept'] in x:
x[i['Dept']].append(i['Name'])
else:
x[i['Dept']] = [i['Name']]
Output:
x -> {'0999': ['Tina'], '0123': ['Tom', 'Cheryl', 'Raj']}
Run Code Online (Sandbox Code Playgroud)
是否可以在字典理解或任何其他更pythonic的方式中实现上述逻辑?
字典理解,即使不是不可能,也可能不是最好的选择。我可以建议使用defaultdict
(https://docs.python.org/2/library/collections.html#collections.defaultdict):
from collections import defaultdict
dic = defaultdict(list)
for i in data:
dic[i['Dept']].append(i['Name'])
Run Code Online (Sandbox Code Playgroud)
这似乎太复杂了,不能被允许进入任何最重要的代码,但只是为了好玩,你去吧:
{
dept: [item['Name'] for item in data if item['Dept'] == dept]
for dept in {item['Dept'] for item in data}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8021 次 |
最近记录: |