我有這樣一本字典:如何將字典中的鍵與列表中的元素進行匹配,並將這些鍵值存儲到python中的另一個字典中?
{'and': {'in': 0.12241083209661485,
'of': 0.6520996477975429,
'to': 0.7091938791256235},
'in': {'and': 0.12241083209661485,
'of': -0.46306801953487436,
'to': -0.0654517869126785},
'of': {'and': 0.6520996477975429,
'in': -0.46306801953487436,
'to': 0.8975056783377765},
'to': {'and': 0.7091938791256235,
'in': -0.0654517869126785,
'of': 0.8975056783377765}}
和列表如下:
list1 = ['the', 'of', 'Starbcks', 'in', 'share', 'for', '%', 'fiscal', '2007',
'growth', 'year', 'cents', 'earnings', 'a', 'company', '2,400', 'net',
'abot', 'range', 'stores', 'revene', 'sales', 'gidance', '``', "''",
'earnings', 'provides', 'wew', 'net']
我想通過列表來遍歷和檢查取其話等於在列表中的鍵,然後添加這些關鍵值轉換成另一個字典。
從這個例子一樣,我想這是我的結果:
new_dict = {'in': {'and': 0.12241083209661485,
'of': -0.46306801953487436,
'to': -0.0654517869126785},
'of': {'and': 0.6520996477975429,
'in': -0.46306801953487436,
'to': 0.8975056783377765}}
我做這樣的事情:
for elem in l:
temp_dict = dict((key,value) for key,value in similarity_matrix.iteritems() if key == elem)
print temp_dict
但我得到{}
爲我的結果。怎麼了,怎麼解決?
編輯:
現在,我把這個:
OrderedDict(for k in list1:
if k in d:
new_d[k] = d[k]
else:
new_d[k] = 0)
即,是不是有鑰匙,將得到的值0 new_d。但是,有沒有辦法以與list1中的單詞相同的順序獲取字典?
等的輸出應該是:
new_d : {'the' : 0, 'of': {'and': 0.6520996477975429, 'in': -0.46306801953487436,'to': 0.8975056783377765}, 'Starbucks' : 0, ......}
只匹配主鍵?被發現然後 – Hackaholic 2014-11-14 22:26:49