【发布时间】:2015-07-17 21:12:28
【问题描述】:
假设我有以下字典(我正在使用的字典要大得多):
dict1={1:["item", "word", "thing"], 2:["word", "item"], 3:["thing", "item", "item"]}
并将字典中使用的每个单词都存储在一个列表中:
all_words=["item", "word", "thing"]
我想通过字典子列表运行列表中的每个单词,并返回找到它们的所有子列表的键,并将它们存储在元组中。所以我想得到:
dict2={"item":(1, 2, 3), "word":(1, 2), "thing":(1, 3)}
这就是我所拥有的:
dict2={}
for word in all_words:
for key, sublist in dict2.items():
for word in sublist:
if word not in sublist:
dict2[word]=dict2[word]+key
else:
dict2[word]=key
【问题讨论】:
-
那么问题出在哪里?
-
我猜
if word not in sublist:应该是if word not in dict2:? -
你为什么要遍历
dict2.items()? -
还有一个问题:
dict2[word]+key不起作用;您不能将tuple添加到int。但是dict2[word] + (key,)可以。当然,dict2[word] = (key,)首先使它成为一个元组。如果你解决了这个问题,以及其他两个问题(提示:如果你给你的变量起比dict1更好的名字,那么犯这样的错误可能会更难),你的代码应该可以工作。但是,您可能希望查看setdefault方法和/或defaultdict类,以使其不那么冗长、更易于阅读、更难搞砸并且可能更高效。 -
明确指出,您既不应该迭代
dict2,也不应该迭代dict1.items()。你应该只迭代dict1。
标签: python search dictionary sublist