我有这个:
names = {"Micky": "Mouse", "Goofy": "Black", "Pit": "Black", "Donald": "Trump"}
我希望用for循环迭代这个字典,但"Black"
只迭代一次。
如下所示:
for value in names.iter_only_once_values():
print value
Output: "Mouse" , "Black" , "Trump"
这可能吗?如何?
答案 0 :(得分:5)
你可以这样做:
for value in set(names.values()):
print value
使用集合将删除任何重复项。上面的输出是:
Mouse
Black
Trump
或者,您可以使用https://docs.python.org/2/library/itertools.html中的unique_everseen
食谱:
for value in unique_everseen(names.itervalues()):
print value
答案 1 :(得分:0)
你可以试试这个:
for key in {k: v for v, k in names.iteritems()}:
print(key)
这会将字典设置,值作为键和键作为值反转。因此,您将获得所需的输出:
Mouse
Black
Trump
答案 2 :(得分:0)
另一种方法:
for name in dict.fromkeys(names.values()).keys():
print name
输出:
Mouse
Black
Trump
当您需要使用OrderedDict
代替dict
时,此方法非常有用,例如:
from collections import OrderedDict
# dictionary names is sorted by values
ordered_names = OrderedDict(sorted(names.items(), key=lambda t: t[1]))
# dictionary names is printed in desired order
for name in OrderedDict.fromkeys(ordered_names.values()).keys():
print name
输出:
Black
Mouse
Trump