[英]How do I create a list as a dictionary entry for a specific key in Python?
I am iterating through a file looking for certain attributes in each line, and if the line matches I want to insert it as an item in a list for a particular dictionary key. 我正在遍历文件,在每一行中查找某些属性,如果该行匹配,我想将其作为项插入到特定字典键的列表中。
For example: 例如:
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']
Should print ['aaron', 'charlie']. 应该打印['aaron','charlie']。
The reason I'm asking this is because I'm not sure how else to create multiple entries for a key in a dictionary. 我之所以这样问,是因为我不确定如何在字典中为键创建多个条目。
You can use python's defaultdict
for this purpose. 您可以为此使用python的defaultdict
。 It will automatically generate a list as a default value for the dictionary. 它将自动生成一个列表作为字典的默认值。
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']
Output: 输出:
['aaron', 'charlie']
The OP has indicated in a comment that he wants heterogenous values in his dictionary. OP在评论中指出,他希望字典中包含异构值。 In that case a defaultdict
may not be appropriate and instead he should just special case those two cases. 在那种情况下, 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']
I think it is a good use case for the setdefault
method of the dict
object: 我认为这对于dict
对象的setdefault
方法是一个很好的用例:
d = dict()
for name in list_of_names:
if 'a' in name:
d.setdefault("has_a", []).append(name)
You can use key
function to get list of keys and check if adding is needed. 您可以使用key
功能来获取按键列表并检查是否需要添加。 Then append as always. 然后像往常一样追加。
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.