'Manipulate an object inside a list in python

I'm trying to learn how to create hash table in Python. I want to manipulate an object list inside a list, here is my code:

import math

class ht_input:
    def __init__(self, string):
        self.string = string
        self.count = 1
        
class HashTable:
    def __init__(self, size):
        self.MAX = size
        self.collission = 0
        self.arr = [[] for i in range(self.MAX)]
    
    #Start of Divison method hashing function
    #Get the prime numbers <= to the size
    def get_prime(self):
        primes = list()
        numbers = [True for i in range(self.MAX + 1)]
        for i in range(2, self.MAX + 1):
            if numbers[i]:
                primes.append(i)
                for n in range( i ** 2, self.MAX + 1, i):
                    numbers[n] = False
        final_prime = primes[len(primes) - 1]
        return final_prime
    
    #Hash function1: Divison method
    def div_hash(self, this_input):
        numeric_text = 0
        for char in this_input.string:
            numeric_text += ord(char)
        return numeric_text % self.get_prime()
    
    def add_item(self, this_input):
        s = ht_input(this_input)
        print(f"Input: {s.string}")
        if s.string in (item for sublist in self.arr for item in sublist):
            print(f"{s.string} found!")
            s.count += 1
        else:
            h = self.div_hash(s)
            print(f"Hashed to: {h}")
            self.arr[h] = [s.string, s.count]

Here is my sample run:

ht = HashTable(12)
ht.arr
[[], [], [], [], [], [], [], [], [], [], [], []]
ht.add_item("facebook")
Input: facebook
Hashed to: 1
ht.arr
[[], ['facebook', 1], [], [], [], [], [], [], [], [], [], []]
ht.add_item("facebook")
Input: facebook
facebook found!
ht.arr
[[], ['facebook', 1], [], [], [], [], [], [], [], [], [], []]

As you can see, on the second ht.add_item("facebook"), I want to manipulate the count of facebook in the array to:

  • [[], ['facebook', 2], [], [], [], [], [], [], [], [], [], []]

and so on..



Solution 1:[1]

You can use for loop for doing this.

for item in list:
  item.update((k, "2") for k, v in item.items() if v === "1")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Apensia