如何使用Python函数将多个值添加到键中

时间:2019-08-05 15:54:26

标签: python dictionary

switch createAppDirectory(searchPath) {
case .success: return .success(())
case .failure(let error): return .failure(error)
}

我的输出:

class my_dict(dict): 

    # __init__ function 
    def __init__(self): 
        self = dict() 

    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value

    # Function to remove key:value 
    def removekey(self,key):
        del self[key]


dict_obj = my_dict() 
dict_obj.add('key1', 'value1') 
dict_obj.add('key2', 'value2') 
dict_obj.add('key1', 'value3')
print(dict_obj) 

所需的输出:

{'key1': 'value3', 'key2': 'value2'}

我编写了一个程序,试图将这些值添加到键中。如何使用 add 函数插入多个值?

{'key1': ['value1','value3'], 'key2': ['value2']}

3 个答案:

答案 0 :(得分:4)

只需对您的add函数进行更改即可解决问题-

def add(self, key, value): 
    try: 
        self[key].append(value) 
    except KeyError:  # if key does not exist
        self[key] = [value]  # add that key into the dict

输出-

{'key1': ['value1', 'value3'], 'key2': ['value2']}

答案 1 :(得分:3)

将您的自定义“ home” 类更改为以下内容(以获得所需的结果):

class my_dict(dict):    
    def add(self, key, value):
        self.setdefault(key, []).append(value)

    def remove_key(self, key):
        del self[key]


dict_obj = my_dict()
dict_obj.add('key1', 'value1')
dict_obj.add('key2', 'value2')
dict_obj.add('key1', 'value3')
print(dict_obj)  # {'key1': ['value1', 'value3'], 'key2': ['value2']}

答案 2 :(得分:2)

除非您的用例更多,否则建议使用defaultdict

from collections import defaultdict
mydict = defaultdict(list)
mydict['key1'].append('value1')
mydict['key1'].append('value3')
mydict['key2'].append('value2')

enter image description here