-2

I'm just hoping i can get some help with adding multiple values to a specific key. i understand how to change a value and add a new key and its value. i just can't get multiple values with one key. The problem I'm having is that I'm not sure what the value will be that added to the key given. is there any method to add values to a key in python.

I'm running version 3.4

Thanks

i've tried appending values but it comes up with errors such as unhashable type: 'slice', object is not subscriptible

Brendan
  • 1
  • 1
  • 1
  • 1
    Guess your question is there are multiple values has same key in a dictionary. http://stackoverflow.com/questions/20585920/how-to-add-multiple-values-to-a-dictionary-key-in-python – owenwater Nov 30 '14 at 06:11

1 Answers1

1

It's not entirely clear what you're wanting to do, but if you just want a list of values for a particular key, one easy way of doing that is with dict.setdefault

my_dict = {}
my_dict.setdefault('key_name', []).append('value')
print(my_dict)

Out[416]: {'key_name': ['value']}

my_dict['key_name'].append('new_value')
print(my_dict)

Out[417]: {'key_name': ['value', 12]}

If this isn't what you'd hoped for, you can always write a class that captures the desired behavior, but it seems like it might be a trap. :)

class AppendDict(dict):
"""Just like dict, except it appends to existing values instead of overwriting them"""
def __setitem__(self, key, value):
    if (key in self) && (type(self[key]) is list):
        self[key].append(value)
    else:
        super(AppendDict, self).__setitem__(key, value)
Gabriel
  • 21
  • 6