简体   繁体   English

如何在Python中为特定键创建列表作为字典条目?

[英]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.

相关问题 如何访问 python 中字典中的某个列表条目? - How do I access a certain list entry in a dictionary in python? 如何在python字典中创建具有key和key变量的列表? - How do I create a list inside python dictionary having key and key variable? 如何在 python 字典中的特定索引处获取密钥? - How do i get the key at a specific index in a python dictionary? 如何在Python中创建以列表为键的字典? - How could I create a dictionary in Python with a list as a key? Python:如何创建以列表条目命名的字典? - Python: How to create a dictionary named after a list entry? 如何使用 Python 中的特定键从字典列表中创建字典 - How to create a dictionary from a list of dictionary using specific keys in Python 如何使用python从列表中获取字典,将列表条目作为键,并将列表中的项数作为值? - How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python? 如何创建一个列表作为字典的键并添加到不同的零件列表中? - How do I create a list as a key of a dictionary and add to the in different parts list? 如何删除列表中的特定附加字典(即其键和值) - How do you delete a specific appended dictionary (i.e. its key and value) in a list 如何遍历字典列表并选择特定的键值python - How to loop through a list of dictionary and select specific key value python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM