我需要一个defaultdict,可以从第一个文件中获取finaldict
一个查询字列表。
最终的dict是两个文件中一对共享相同ID的单词的字典。例如foo, oof
共享相同的1243
和1453
ID。这是为了方便以后进行单词对搜索,当我尝试搜索('foo','oof')
时,它将返回['1243','1453']
。
如果我搜索('foo','duh')
的最终结果,它将不会返回任何内容,因为wordpair不会共享任何相同的ID。
query = ['foo','barbar']
finaldict = defaultdict(list)
finaldict = {('foo','oof'):['1243','1453']
('foo','rabrab'):['2323']
('barbar','duh'):['6452']}
我一直这样做,但有更简单的方法来实现finaldict
吗?
query = ['foo','barbar']
from collections import defaultdict
dict1 = defaultdict(list)
dict2 = defaultdict(list)
dict1['foo'] = ['1234','1453','2323'];
dict1['bar'] =['5230']; dict1['barbar'] =['6452']
dict2['1243']=['oof']
dict2['1453']=['oof']
dict2['4239']=['rba']
dict2['2323']=['rabrab']
dict2['6452']=['duh']
tt = defaultdict(defaultdict)
for p in sorted(query):
for ss in sorted(dict1[p]):
if len(dict2[ss]) != 0 and dict2[ss] != None:
tt[p][ss] = dict2[ss]
finaldict = defaultdict(set)
for src in tt:
for ss in tt[src]:
for trg in tt[src][ss]:
finaldict[(src, trg)].add(ss)
print finaldict[('foo','oof')]
以上代码输出:
>>> print finaldict[('foo','oof')]
set(['1453'])
>>> for i in finaldict:
... print i, finaldict[i]
...
('foo', 'rabrab') set(['2323'])
('barbar', 'duh') set(['6452'])
('foo', 'oof') set(['1453'])
答案 0 :(得分:1)
{(k1,v):k2 for k1 in dict1 for k2 in dict2
for v in dict2[k2] if k2 in dict1[k1]}
{('barbar','duh'):'6452',('foo','oof'):'1453',('foo','rabrab'):'2323'}