Dictionary comprehension and checking for keys during creation
I had this task to read a file, store each character in a dict as key and increment value for each found key, this led to code like this:
chrDict = {}
with open("gibrish.txt", 'r') as file:
for char in file.read():
if char not in chrDict:
chrDict[char] = 1
else:
chrDict[char] += 1
So this works ok but to 开发者_JAVA技巧me, atleast in Python, this looks really ugly. I tried different ways of using comprehension. Is there a way to do this with comprehension? I tried using locals() during creation, but that seemed to be really slow, plus if I've understood anything correctly locals would include everything in the scope in which the comprehension was launched, making things harder.
In Python 2.7, you can use Counter
:
from collections import Counter
with open("gibrish.txt", 'r') as file:
chrDict = Counter(f.read())
Use defaultdict:
from collections import defaultdict
chr_dict = defaultdict(int)
with open("gibrish.txt", 'r') as file:
for char in file.read():
chr_dict[char] += 1
If you really want to use list comprehensions, you can use this inefficient variant:
text = open("gibrish.txt", "r").read()
chr_dict = dict((x, text.count(x)) for x in set(text))
Dictionary get() method is going to return you the value if it exists or else 0.
chrDict = {}
with open("gibrish.txt", 'r') as file:
for char in file.read():
chrDict[char] = chrDict.get(char, 0) + 1
精彩评论