Search code examples
pythondictionarytxt

converting txt file to dictionary to count ".csv"


`I have to count ".csv" in each line and assign them to the same key value.

I have text file "files.txt" with 7 line of

test/file1.txt    
test/file2.txt.gz      
test/file3.csv     
test/file4.txt     
test2/file5.csv        
test2/file6.txt     
test2/file7.csv      

Here's my code:

res = {}
for line in open('files.txt').readlines():
    key, val = line.strip().split('/')
    x =0
    if '.csv' in val:
        x+=1
        print(key, ":", x)

which yields the following output:

test : 1      
test2 : 1    
test2: 1     

notice that I am new to programing`


Solution

  • Here, I've kept your code intact, but made used of the res dictionary to count the total number of occurrences of '.csv' for each key:

    res = {}
    for line in open('files.txt').readlines():
        key, val = line.strip().split('/')
        if '.csv' in val:
            res[key] = res.get(key, 0) + 1
    for key, val in res.items():
        print(f"{key}:{val}")
    
    # test:1
    # test2:2