I have solved a problem to count pairs of values in an inputted array using dictionaries in Python.
Problem Example:
Input:
[1,1,2,3,2]
Output:
2 (since there are a pair of 1's and a pair or 2's)
Code Snippet:
dict = {}
for i in range(len(ar)):
if ar[i] in dict:
dict[ar[i]] += 1
else:
dict[ar[i]] = 1
Full Code if interested: https://pastebin.com/s1LQRQMC
In the above code, I am using an if statement to check if an array element has been added to the dictionary and adding to it's count if it has. Else, I'm initializing the array element as a key and setting its value as 1.
My question is if there are any ways in python to simplify the if/else statement that may be cleaner or more acceptable or considering alternate ways using structure of the dictionary.