Reputation: 11
If I have a txt file:
apple:fruit
banana: fruit
carrot: vegetable
lettuce: vegetable
How could I get a dictionary that:
{fruit:[apple, banana], vegetable: [carrot, lettuce]}
Thank you in advance!
Upvotes: 0
Views: 77
Reputation: 123423
It's fairly easy to create your own dictionary subclass. One advantage besides not needing to import
anything that it has over using defaultdict(list)
is that it prints like a normal dictionary.
class Vividict(dict):
def __missing__(self, key):
value = self[key] = list()
return value
vividict = Vividict()
with open('fruits.txt') as file:
for line in file:
name, kind = line.replace(':', ' ').split()
vividict[kind].append(name)
from pprint import pprint
pprint(vividict, width=40)
Output:
{'fruit': ['apple', 'banana'],
'vegetable': ['carrot', 'lettuce']}
Upvotes: 0
Reputation: 1383
Use collections defaultdict
to maintain the list.
from collections import defaultdict
res_dict = defaultdict(list)
with open('file.txt', 'r') as f:
for line in f:
value, name = line.rstrip().split(':')
res_dict[name.strip()].append(value)
Upvotes: 1
Reputation: 71570
Try using:
with open('file.txt', 'r') as f:
lines = [line.rstrip().split(': ') for line in f]
print({k: [line[0] for line in lines if line[1] == k] for _, k in lines})
Upvotes: 0
Reputation: 649
file = open("text.txt", "r")
lines = file.readlines()
dict = {}
for line in lines:
try:
dict[line.split(":")[1].strip()].append(line.split(":")[0].strip())
except:
dict[line.split(":")[1].strip()] = [line.split(":")[0].strip()]
i hope this helps you next time before you ask research more about your problem and try some codes on your own so that you can learn more about coding :))
Upvotes: 1