所以我有两本词典。
Dictionary 1 looks like this: {'aaien': ['01, 02, 12'], 'aan': ['10']}
Dictionary 2 looks like this: {'01:': ['pronoun'], '02': ['I'],'03': ['we']}
现在我想编写一个结合了这两个词典的函数或代码,结果应该是: 'aaien':['代词,我,影响']
这是我到目前为止所得到的:
for word, nums in d1.items():
print word, "->",
for num in nums:
if d2.has_key(num):
print d2[num],
print
答案 0 :(得分:1)
使用collections.defaultdict()
:
In [60]: dic1= {'aaien': ['01, 02, 12'], 'aan': ['10']}
In [61]: dic2={'01': ['pronoun'], '02': ['I'],'03': ['we']} # after fixing '01:'
In [62]: dic3=defaultdict(list)
In [63]: for x,y in dic1.items():
keys=map(str.strip,y[0].split(",")) #split at ",", and then apply str.strip
for k in keys:
if k in dic2: #if key is present in dic2
dic3[x].extend(dic2[k])
....:
In [64]: dic3
Out[64]: defaultdict(<type 'list'>, {'aaien': ['pronoun', 'I']})
答案 1 :(得分:0)
我建议你先修复你的dicts,然后使用dict.setdefault
:
d1 = {k:map(str.strip,v[0].split(',')) for k,v in d1.iteritems()}
d2 = {k.strip(':'):v for k,v in d2.iteritems()}
result = {}
for k,v in d1.iteritems():
for i in v:
if i in d2:
result.setdefault(k,[]).extend(d2[i])
print result
输出:
{'aaien': ['pronoun', 'I']}
答案 2 :(得分:0)
首先“修复”你的词汇(正如其他人所建议的那样) 我希望他们看起来像这样。
d1 = {'aaien': ['01', '02', '12'], 'aan': ['10']}
d2 = {'01': 'pronoun', '02': 'I', '03': 'we'}
然后试试这个:
print {k: [d2.get(l) for l in v] for k, v in d1.iteritems()}
{'aaien': ['pronoun', 'I', None], 'aan': [None]}
值已被替换,无值放在没有可用值的位置。
如果您真的打算让查找字典(d2)值为值列表,我需要更多信息。你想要列表还是扁平化?
即。查找
d2 = {'01': ['pronoun'], '02': ['I', 'spam'], '03': ['we']}
你想要哪一个
{'aaien': ['pronoun', 'I', 'spam', None], 'aan': [None]}
{'aaien': ['pronoun', ['I', 'spam'], None], 'aan': [None]}