Search code examples
pythondictionarycounterletter

Merging Two Dictionaries Values If They have The Same Keys


I am making a list word counter and trying to merge two dictionaries that have a counter for each character, but I keep getting the wrong outputs. Here is what I attempted in an effort to figure out why. Everything seems to go well except for the last two keys in the dictionary.

counts = {"a": 1, "p": 2, "l": 1, "e": 1}
new_counts = {"h": 1, "e": 1, "l": 2, "o": 1}

counts.update(new_counts)

for letters in counts:
    if letters in counts and new_counts:
        counts[letters] += 1
    else:
        counts[letters] = 1

print(counts)

What I need:

{"a": 1, "p": 2, "l": 3, "e": 2, "h": 1, "o": 1}

What I get:

{'a': 2, 'p': 3, 'l': 3, 'e': 2, 'h': 2, 'o': 2}

Solution

  • You can use a simple for-loop:

    counts = {"a": 1, "p": 2, "l": 1, "e": 1}
    new_counts = {"h": 1, "e": 1, "l": 2, "o": 1}
    
    for k, v in new_counts.items():
        if k in counts:
            counts[k] += v
        else:
            counts[k] = v
    
    print(counts)  # => {'a': 1, 'p': 2, 'l': 3, 'e': 2, 'h': 1, 'o': 1}
    

    This is actually the fastest method. I tested it with timeit against kosciej16's answer and his took 5.49 seconds, while mine took 0.73 seconds (for one million iterations). I also tested against wim's dictionary comprehension answer and that took 1.95 seconds, while mine took 0.85 seconds.