Search code examples
pythonpython-3.xlistdictionarysum

How to add values of a single key in a dictionary


Say I have a dictionary:

a_dictionary = {"a": [1, 2], "b": [3, 4]}

I want to get a resultant dictionary that has the value:

a_dictionary = {"a": [3], "b": [7]}

Can someone please help me?


Solution

  • Try this:

    for k,v in a_dictionary.items():
        a_dictionary[k] = [sum(v)]
    

    Output:

    >>> print(a_dictionary)
    {'a': [3], 'b': [7]}