user1464878
user1464878

Reputation:

How to add multiple values into a key with a Python function

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)

Upvotes: 4

Views: 226

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 2

Sushant
Sushant

Reputation: 3669

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

Upvotes: 3

David Zemens
David Zemens

Reputation: 53623

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

Upvotes: 2

Related Questions