Reputation: 378
I have a problem when I want to extract some labels from file. I'm talking about 2000 labels, and I would like to use them from file and give them some size characteristic.
with open("filename") as f:
content = f.readlines()
nsize= { "Mary": 1, "John": 1, "Jack": 1, "Ted": 5 }
this is example for 4 labels. I need it for all 2000. What is the easiest way to do that?
Upvotes: 0
Views: 59
Reputation: 1121216
Use a dict comprehension:
with open("filename") as f:
nsize = {el.strip(): len(el.strip()) for el in f}
This takes each line in f
, strips()
away whitespace, turns it into the key and the length of the label as the value.
If you meant to count them, use collection.Counter
:
from collections import Counter
with open("filename") as f:
nsize = Counter(el.strip() for el in f)
This takes each label from the file (again, strip()
ing away extra whitespace), and the Counter
dict will give you a count for each label in the file (so if label foo
appears twice, nsize['foo']
is 2).
Upvotes: 2