我有以下字典:{26:['hello', 'test'], 27:['hello', 'good', 'morning', 'test']}
我需要创建一个新字典,以单词作为关键字,将列表作为值作为值,其中的键作为值,它应该是这样的:dict1 = {'hello':[26,27], 'test':[26,27], 'good':[27], 'morning':[27]}
为了解决我的问题,我已经创建了所有单词没有重复的列表,所以words = ['hello', 'test', 'good', 'morning']
. 然后我尝试了这个:
newdict = {}
for i in words:
l = []
for k in dict1:
if i in dict1[k]:
l.append(k)
newdict[i] = l
你能帮助我吗?提前致谢。
如果没有导入,您可以这样做:
a = {26:['hello', 'test'], 27:['hello', 'good', 'morning', 'test']}
result = {}
for k, v in a.items():
for item in v:
result[item] = result.get(item, []) + [k]
这dict. get(key[, default])
是解释here。因此,您的结果 dict 将返回它的值或空列表。
之后,您可以简单地使用+
运算符,它是列表的连接运算符。
请注意,列表连接仅适用于列表之间,因此我们将值包装起来,[]
使其成为包含键的列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句