Search code examples
python-3.xdictionarykeyvaluepair

Python3 - How to read words from a list as keys, and then count and store their occurrence as values to the keys


I am getting information from a file which has content such as the one below:

1:Record:Place1:Ext12 2:Record:Place2:Ext2 3:Record:Place1:Ext19 4:Record:Place1:Ext12

I am trying to store words such as Place1 and Place2 in dictionary as keys and then count their occurrences and store the integer count as values to those keys respectively.

file = open('./Records.txt', mode='r')
d_file = file.read()

location = dict()
count = 0

for item in d_file.splitlines():
    items = item.split(':')
    key = items[2]
    if key == items[2]:
       count += 1
       location[key] = count

print(location)

Solution

  • There is a Counter feature in the collections module. (Click to read official documentation)

    It does exactly what you want. It takes an iterable or mapping and returns a dict of keys and number of occurrences as value.

    from collections import Counter
    #open file, etc
    keys = [item.split(':')[2] for item in d_file.splitlines()]
    print(Counter(keys))
    

    In the above snippet, a list of all key occurrence is made according to your format, then a dictionary of number of occurrences is printed.

    The file is assumed to have correctly formatted lines, so item.split(':')[2] exists. I recommend looking at this answer for safer str partitioning How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?