In case if order of dicts in final_list
DOESN'T matter:
from collections import defaultdict
with open('/home/bwh1te/projects/stackanswers/wordcount/data.txt') as f:
occurencies = defaultdict(list)
for line in f:
key, value = line.strip().split()
# invoke of occurencies[key] in this condition
# cause autocreating of this key in dict
if value not in occurencies[key] and value.isalpha():
occurencies[key].append(value)
# defaultdict(<class 'list'>, {'C': ['r', 'l'], 'D': ['a', 'd'], 'S': ['o'], 'A': ['l'], 'R': []})
# Use it like a simple dictionary
# In case if it must be a list, not a dict:
final_list = [{key: value} for key, value in occurencies.items()]
# [{'C': ['r', 'l']}, {'D': ['a', 'd']}, {'S': ['o']}, {'A': ['l']}, {'R': []}]
In case if order of dicts in final_list
DOES matter:
from collections import OrderedDict
with open(file_path) as f:
occurencies = OrderedDict()
for line in f:
key, value = line.strip().split()
# Create each key anyway
if key not in occurencies:
occurencies[key] = []
if value.isalpha():
if value not in occurencies[key]:
occurencies[key].append(value)
# OrderedDict([('A', ['l']), ('C', ['r', 'l']), ('D', ['a', 'd']), ('R', []), ('S', ['o'])])
# In case if it must be a list, not a dict
final_list = [{key: value} for key, value in occurencies.items()]
# [{'A': ['l']}, {'C': ['r', 'l']}, {'D': ['a', 'd']}, {'R': []}, {'S': ['o']}]
list1 = [{key: value} for key, value in occurencies.items() if value]
# [{'A': ['l']}, {'C': ['r', 'l']}, {'D': ['a', 'd']}, {'S': ['o']}]
Or you can implement hybrid of OrderedDict and defauldict like that: Can I do an ordered, default dict in Python? :)