您可以使用python的defaultdict
来达到此目的。它会自动生成一个列表作为字典的默认值。
from collections import defaultdict
mydict = defaultdict(list)
list_of_names = ['aaron', 'boo', 'charlie']
for name in list_of_names:
if 'a' in name:
mydict['has_a'].append(name)
print mydict['has_a']
输出:
['aaron', 'charlie']
的OP已,他希望在他的字典里异质值的评论表示。在这种情况下,defaultdict
可能不合适,而应该只是特例处理这两种情况。
# Initialize our dictionary with list values for the two special cases.
mydict = {'has_a' : [], 'has_b' : []}
list_of_names = ['aaron', 'boo', 'charlie']
for name in list_of_names:
if 'a' in name:
mydict['has_a'].append(name)
# When not in a special case, just use the dictionary like normal to assign values.
print mydict['has_a']
我宁愿不这样做,因为我的许多其他键指的是布尔值而不是列表。我的字典中只需要2个列表。 – Michi
@Michi,在这种情况下,只需将两个特殊情况添加到您的循环中即可。我会更新答案。 – merlin2011
它的工作原理 - 谢谢! – Michi