我有一本这样的字典:
{'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)
也就是说,不存在的键在new_d中的值为0。但是,有什么方法可以使字典与list1中的单词具有相同的顺序吗?
像这样的输出应该是:
new_d : {'the' : 0, 'of': {'and': 0.6520996477975429, 'in': -0.46306801953487436,'to': 0.8975056783377765}, 'Starbucks' : 0, ......}
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']
d={'and': {'of': 0.6520996477975429, 'in': 0.12241083209661485, 'to': 0.7091938791256235}, 'of': {'and': 0.6520996477975429, 'to': 0.8975056783377765, 'in': -0.46306801953487436}, 'in': {'and': 0.12241083209661485, 'of': -0.46306801953487436, 'to': -0.0654517869126785}, 'to': {'and': 0.7091938791256235, 'of': 0.8975056783377765, 'in': -0.0654517869126785}}
new_d ={}
for k in list1:
if k in d:
new_d[k] = d[k]
print(new_d)
{'of': {'and': 0.6520996477975429, 'to': 0.8975056783377765, 'in': -0.46306801953487436}, 'in': {'and': 0.12241083209661485, 'of': -0.46306801953487436, 'to': -0.0654517869126785}}
或dict理解:
new_d ={ k: d[k] for k in list1 if k in d}
检查键是否在字典或集合中 O(1)
使用您自己的代码,您可以执行以下操作检查密钥是否在列表中:
temp_dict = dict((key,value) for key,value in d.iteritems() if key in set(list1))
为了保持添加项目的顺序,您需要使用collections.OrderedDict:
from collections import OrderedDict
new_d = OrderedDict(((k,d[k]) if k in d else (k,0) for k in list1 ))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句