Search code examples
pythondictionarysimulator

Updating integer values of a dictionary in python


I have a dictionary with 3 values associated to each key,

I want to know how to increment the values of noTaken & totalBranch as i pass through the data file, as my current method doesn't change the values, the output of lookup gives me (1,1,0) or (0,1,0) - i need the first two values to increase

for line in datafile.readlines():
    items = line.split(' ')
    instruction = items[1]
    if lookup.has_key(instruction):
        if (taken == 1):
            lookup[instruction] = (noTaken + 1, totalBranch + 1, prediction)
        else:
            lookup[instruction] = (noTaken, totalBranch + 1, prediction)
    else:
        if (taken == 1):
            lookup[instruction] = (1, 1, prediction)
        else:
            lookup[instruction] = (0, 1, prediction)

(noTaken, prediction & totalBranch are all initialised as 0 above this) Thanks in advance!


Solution

  • A cleaner way to initialize is to use defaultdict , then you can directly refer to elements in dict values e.g.

    from collections import defaultdict
    
    lookup = defaultdict(lambda: [0,0,0])
    
    lookup['a'][0] += 1
    lookup['b'][1] += 1
    lookup['a'][0] += 1
    
    print lookup
    

    output:

    {'a': [2, 0, 0], 'b': [0, 1, 0]}
    

    Also note that I am defaulting value to a list instead of tuple so that we can modify values in place, tuple being immutable can't be modified