4
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) 

My Output:

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

Desired output:

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

I have written a program to try to add the values into a key. How do I insert more than one value using the add function?

for d in self.dict():
    for l, m in d.items():  
        dict.setdefault(l, []).append(m)

3 Answers 3

3

A simple change to your add function should do the trick -

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

Output -

{'key1': ['value1', 'value3'], 'key2': ['value2']}
Sign up to request clarification or add additional context in comments.

Comments

2

Unless there is more to your use-case, suggest using defaultdict:

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

enter image description here

Comments

2

Change your custom "home" class to the following (to get the needed result):

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']}

1 Comment

I was doing this :P. Nice answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.