seeking how to merge

Viewed 61

is my code still salvageable? Here's a snippet of me trying to find the amount of times a letter in the alphabet (both upper and lower case) shows up in a text paragraph. This code successfully works for making two separate lists of lower and upper case letters, but I'm trying to merge them into one. I thought I could input a def merge() but it didn't work and I have a feeling I might have to start completely over.

small_letter_status = [0]*26
capital_letter_status = [0]*26

for x in txt:
    if x>='a' and x<='z':
        small_letter_status[ord(x)%ord('a')] += 1
    elif x>='A' and x<='Z':
        capital_letter_status[ord(x)%ord('A')] += 1

print("\nSmall Letter count")
for x in range(len(small_letter_status)):
    print(chr(x+(ord('a'))), small_letter_status[x])

print("\nCapital Letter count")
for x in range(len(capital_letter_status)):
    print(chr(x+(ord('A'))), capital_letter_status[x])
3 Answers

You can simply merge lists using + operator

print([1, 2, 3] + [4, 5,6])
-> [1,2,3,4,5,6]

You would be best advised to use collections.Counter for this.

>>> from collections import Counter
>>> s = "hello world"
>>> dict(Counter(ch for ch in s if ch.isalpha()))
{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}

If you want a dictionary using all upper and lowercase letters as keys, with value 0.

>>> from string import (ascii_lowercase, ascii_uppercase)
>>> d = {c: 0 for c in ascii_lowercase + ascii_uppercase}
>>> d
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0, 'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0}

You can then update it with the counts from the string.

>>> d.update(dict(Counter(ch for ch in s if ch.isalpha())))
>>> d
{'a': 0, 'b': 0, 'c': 0, 'd': 1, 'e': 1, 'f': 0, 'g': 0, 'h': 1, 'i': 0, 'j': 0, 'k': 0, 'l': 3, 'm': 0, 'n': 0, 'o': 2, 'p': 0, 'q': 0, 'r': 1, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 1, 'x': 0, 'y': 0, 'z': 0, 'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0}

Try this one:

from string import (ascii_lowercase, ascii_uppercase)
lower_count = list(zip(ascii_lowercase, small_letter_status))
upper_count = list(zip(ascii_uppercase, capital_letter_status))
lower_count + upper_count

The Output:

[('a', 0),
 ('b', 0),
 ('c', 0),
 ('d', 2),
 ('e', 0),
 ('f', 2),
 ('g', 0),
 ('h', 2),
....
('A', 0),
 ('B', 0),
 ('C', 0),
 ('D', 2),
 ('E', 0),
 ('F', 1),
 ('G', 0),
 ('H', 2),
...
Related