Home > front end >  Sum integer value in dict when dict values have strings and integers
Sum integer value in dict when dict values have strings and integers

Time:11-27

Having a dictionary like

{'bob': (1, 'bob'), 'alicia': (3, 'alicia')}

How can I add for example 1 to value [0] in values() of 'bob' key?

So I want something like

{'bob': (2, 'bob'), 'alicia': (3, 'alicia')}

I've tried this

list1 = ['bob', 'alicia', 'bob'] 
d = {}
for i in list1:
    if i not in d:
        d = 1, i
    else:
        d  = 1, i

But 'tuple' object does not support item assignment.

I do not want lists in values dictionary. Thanks

CodePudding user response:

Tuples are ment to be immutable. Thus, editing a tuple is a break of contract. If you want to change the value within the tuple, you will have to construct a new one.

data = {'bob': (1, 'bob'), 'alicia': (3, 'alicia')}
data['bob'] = (data['bob'][0]   1, data['bob'][1])
print(data)

# Out[0]: {'bob': (2, 'bob'), 'alicia': (3, 'alicia')}

You could also create a mutable counter object that you store in the tuple, something along the lines of

class Counter:
    def __init__(self, start: int = 1):
        self._num = start

    @property
    def value(self):
        return self._num

    def increment(self):
        self._num  = 1

    def __repr__(self):
        return str(self._num)


data = {'bob': (Counter(), 'bob'), 'alicia': (Counter(3), 'alicia')}
data['bob'][0].increment()
print(data)

# Out[1]: {'bob': (2, 'bob'), 'alicia': (3, 'alicia')}

A nice discussion if the latter makes the tuple mutable or not (and therefore is a break of contract) can be found in the blog of inventwithpython.com.

  • Related