我有以下代码来创建一个字典,其元素是来自另一个字典的列表:
olddict={'Fiesta': {'key':'Ford'},'Golf': {'key':'Volkswagen'}, 'Bora': {'key':'Volkswagen'} }
newdict = {}
for key, value in olddict.items():
newkey = value['key']
if newkey in newdict:
newdict[newkey].append(key)
else:
newdict[newkey] = [key]
代码工作正常,但似乎完全不是pythonic。也许我有点累,但一线解决方案会很棒......
答案 0 :(得分:2)
>>> olddict={'Fiesta': {'key':'Ford'},'Golf': {'key':'Volkswagen'}, 'Bora': {'key':'Volkswagen'} }
>>> from collections import defaultdict
>>> result = defaultdict(list)
>>> for k, v in olddict.items():
... result[v['key']].append(k)
...
>>> result
defaultdict(<type 'list'>, {'Ford': ['Fiesta'], 'Volkswagen': ['Golf', 'Bora']})
此方法在找到新密钥时初始化空列表。基本上摆脱代码中的else
部分。我不确定你是否可以将defaultdict
与列表理解相结合,使其成为一个单行。
答案 1 :(得分:0)
使用itertools.groupby
。
from itertools import groupby as g
keyfunc = lambda x: olddict[x]['key']
newdict = dict( (k, list(vs)) for k, vs in g(sorted(olddict, key=keyfunc), keyfunc))
如果您使用的是Python 2.7或更高版本,则还可以使用dict理解
newdict = { k: list(vs) for k, vs in g(sorted(olddict, key=keyfunc), keyfunc) }