George
George

Reputation: 5681

python - count files (can't count values in a dictionary)

i want to count files in the command directory based on their extension. So, i created a list with all the files in the cwd ,then a list with only the extensions and then i made a dict from that list.I made the dict with a count parameter but i don't know how to handle this.My dict looks like "{'txt':0,'doc':0}".

 import os,glob

def myfunc(self):
    mypath=os.getcwd() 
    filelist=glob.glob("*") #list with all the files in cwd
    extension_list=[os.path.splitext(x)[1][1:] for x in filelist] #make list with the extensions only
    print(extension_list)

    count=0;
    mydict=dict((x,count) for x in extension_list) #make dict with the extensions as keys and count as value
    print(mydict)

    for i in mydict.values():  #i must do sth else here..
        count+=1
    print(count)
    print(mydict)

Upvotes: 0

Views: 186

Answers (3)

John Gaines Jr.
John Gaines Jr.

Reputation: 11534

This is a perfect use for the collections.Counter class:

>>> from collections import Counter
>>> c = Counter(['foo', 'foo', 'bar', 'foo', 'bar', 'baz'])
>>> c
2: Counter({'foo': 3, 'bar': 2, 'baz': 1})
>>>

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599600

Surely you just want count += i in your loop?

Although there is a nice data structure that does all this for you: collections.Counter.

Upvotes: 1

Platinum Azure
Platinum Azure

Reputation: 46183

Just iterate through the extension list and increment the dictionary value:

for ext in extension_list:
    mydict[ext] += 1

Upvotes: 0

Related Questions