2014-07-01 41 views
2

我遍历一个文件寻找每行中的某些属性,如果行匹配,我想将它作为一个项目插入到特定字典键的列表中。如何创建一个列表作为Python中特定键的字典条目?

例如:

list_of_names = ['aaron', 'boo', 'charlie'] 
for name in list_of_names 
    if color contains 'a': 
     #add here: add to list in dict['has_a'] 
print dict['has_a'] 

应该打印[ '亚伦', '查理']。

我问这个问题的原因是因为我不知道如何为字典中的键创建多个条目。

回答

4

您可以使用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'] 
+0

我宁愿不这样做,因为我的许多其他键指的是布尔值而不是列表。我的字典中只需要2个列表。 – Michi

+0

@Michi,在这种情况下,只需将两个特殊情况添加到您的循环中即可。我会更新答案。 – merlin2011

+0

它的工作原理 - 谢谢! – Michi

2

我认为这是一个很好的用例为dict对象的setdefault方法:

d = dict() 
for name in list_of_names: 
    if 'a' in name: 
    d.setdefault("has_a", []).append(name) 
0

可以使用key函数来获取键列表,如果需要增加检查。然后像往常一样追加。

list_of_names = ['aaron', 'boo', 'charlie'] has_dictionary = {} for name in list_of_names: if name.find('a') != -1: if 'has_a' not in has_dictionary.keys(): has_dictionary['has_a'] = [] has_dictionary['has_a'].append(name) print(has_dictionary['has_a'])

相关问题