0

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.

3 Answers3

0

I think you're looking for defaultdict

from collections import defaultdict
your_dict = defaultdict(int)
for a in arr:
    your_dict[a] += 1
bilke
  • 415
  • 3
  • 6
0

Something like this maybe?

from collections import Counter

socks = [1, 2, 1, 2, 1, 3, 2]

print(sum(count // 2 for count in Counter(socks).values()))
Paul M.
  • 10,481
  • 2
  • 9
  • 15
  • This is a pretty good answer. never used Counter before, but I like this answer alot and does it in a good time complexity. Thanks – Yash Narang Jan 18 '21 at 19:20
0

Of course, you have two alternatives for this:

  1. Counter which will count occurrences of elements in iterables
from collections import Counter

xs = [1, 1, 2, 3, 2]

counts = Counter(xs)

## Counter({1: 2, 2: 2, 3: 1})
  1. defaultdicts which get rid of the if / else statement:
from collections import defaultdict

my_dict = defaultdict(int) # we assing a default type for the keys

xs = [1, 1, 2, 3, 2]

for x in xs:
    my_dict[x] += 1

## defaultdict(int, {1: 2, 2: 2, 3: 1})
Giovanni Rescia
  • 605
  • 5
  • 15
  • Awesome! Thank you and like Paul's Counter answer, you can easily put that into the return/print. Thank you for the help :) – Yash Narang Jan 18 '21 at 19:28