Search code examples
pythondictionarycountdefaultdict

Modify existing value in dictionary (or defaultdictionary) by incrementing that value


I would like to keep a counter for every time a particular value comes up in the list I am scanning.

For example: list:

[(a, 0.2), (b, 1), (a, 0.2), (a, 1)]

I would like a dictionary that can show the following:

mydict = {"a": (# val below 1, # val equal to 1), ...}

Therefore: mydict = {"a": (2, 1), "b" :(0, 1)}

Is there a way to do this with a default dictionary or normal dictionary?

Should I do something like: mydict[mydict["a"]+1] for every value I see either below or equal to 1?


Solution

  • OK, assuming the type of input is an array of arrays and you can store the results as an array in your dictionary, here is how it could be done.

    # Define list of numbers
    lettersNumbersList = [["a", 0.2], ["b", 1], ["a", 0.2], ["a", 1]]
    
    # Here is the dictionary you will populate.
    numberOccurences = {}
    
    # This function is used to increment the numbers depending on if they are less
    # than or greater than one.
    def incrementNumber(letter, number):
    
        countingArray = numberOccurences[letter]
    
        if number < 1:
            countingArray[0] = countingArray[0] + 1
        elif number >= 1:
            countingArray[1] = countingArray[1] + 1
    
        return(countingArray)
    
    # Loops through all of the list, gets the number and letter from it. If the letter
    # is already in the dictionary then increments the counters. Otherwise starts 
    # both from zero.
    for item in lettersNumbersList:
    
        letter = item[0]
        number = item[1]
    
        if letter in numberOccurences:
            numberOccurences[letter] = incrementNumber(letter, number)
    
        else:
            numberOccurences[letter] = [0, 0]
            numberOccurences[letter] = incrementNumber(letter, number)
    
    print(numberOccurences)