I have the below code where I am trying to append a 1 to the hash of an element, on every occurence of it in input.
def test(Ar):
hash_table = {}
for elem in Ar:
if elem not in hash_table:
hash_table.setdefault(elem,[]).append(1)
else:
hash_table[elem] = hash_table[elem].append(1)
print(hash_table)
Ar = (1,2,3,4,5,1,2)
test(Ar)
Output:
{1: None, 2: None, 3: [1], 4: [1], 5: [1]}
Expected Output:
{1: [1,1], 2: [1,1], 3: [1], 4: [1], 5: [1]}
I am puzzled why None gets in on doing an append. Kindly explain what is happening.
Note:
On typing the else portion,
hash_table[elem] = hash_table[elem].append(1) # the append() was not suggested at all by the IDE. I forcibly put it, hoping things will work.