nested for loop not counting correctly

Question:

I have two lists:

common_nodes_list = ['A', 'A', 'B', 'C', 'C', 'C']
uniquePatterns = ['A', 'B', 'C']

I am trying to create a dict with the counts of each unique pattern. Like this:

A: 2
B: 1
C: 3

I have a for loop inside of another for loop:

patternRank = {}

for i in common_nodes_list:
    score = 0
    for pattern in uniquePatterns:
        if pattern == i:
            score += 1   
    patternRank[pattern]=score

patternRank

but It’s only returning:

'C': 1
Asked By: Owen

||

Answers:

Maybe it would be better:

pattern_count = {x: 0 for x in uniquePatterns}
for t in common_nodes_list:
    pattern_count[t] += 1

Your solution will work if you do this modifications:

patternRank = {}

for i in common_nodes_list:
    for pattern in uniquePatterns:
        score = 0 if pattern not in patternRank.keys() else patternRank[pattern]   # <- 
        if pattern == i:
            score += 1   
        patternRank[pattern]=score           # <- Tab

patternRank
Answered By: MaryRa

You should do it the other way: for each pattern in the unique patterns, count how many there are in the common_nodes_list:

common_nodes_list = ['A', 'A', 'B', 'C', 'C', 'C']
unique_patterns = ['A', 'B', 'C']

pattern_rank = {}

for pattern in unique_patterns:
    score = 0
    for node in common_nodes_list:
        if node == pattern:
            score += 1
    pattern_rank[pattern] = score

print(pattern_rank)
>> {'A': 2, 'B': 1, 'C': 3}

And maybe, try to be consistant with the way you name the variables: snake_case or CapWords.

Answered By: nonlinear

An alternative one line:

patternRank = {i: common_nodes_list.count(i) for i in uniquePatterns}
# {'A': 2, 'B': 1, 'C': 3}
Answered By: AboAmmar

we can use a for loop that iterates on the unique_patterns list. then using dict.update({key: value}).

common_nodes_list = ['A', 'A', 'B', 'C', 'C', 'C']
unique_patterns = ['A', 'B', 'C']
char_hist = {}
for char in unique_patterns:
    char_hist.update({char: common_nodes_list.count(char)})
print(char_hist)
Answered By: lroth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.