Reputation: 117
I'm working separating values and keys from a file.So if the word exist in the file add the value to the list. Is it maybe more efficient to use a dictionary and add the values and keys? In the text.txt looks like this:
eggs=2, bread=1, milk=4
eggs=5, bread=2, milk=2
eggs=1, bread=3, milk=3
I want to split the values and keys into separate lists so i can later use this to calculate number of eggs ect
egg_list =[]
with open("text.txt") as f:
for line in f:
lines = f.read().splitlines()# creates a list of the file
lines.split("=") # or split on ","?
if "eggs" in line: # checks if the string "eggs" exists in the list
#if so add the value after"=" into the list
egg_list.append(lines[0]+1)#should list 2,5,1
if "bread" #same for bread ect
Upvotes: 0
Views: 44
Reputation: 4606
We could use itertools.groupby here and by creating a list that holds dictionaries of each line
from itertools import groupby
with open('text.txt') as f:
content = [line.strip('\n ') for line in f]
content = [i.split(',') for i in content]
lista = []
for i in content:
lista.append(dict([j.split('=') for j in i]))
total_eggs= sum([int(k) for k, g in groupby(lista, key=lambda x: x['eggs'])])
print(lista)
# [{'eggs': '2', ' bread': '1', ' milk': '4'}, {'eggs': '5', ' bread': '2', ' milk': '2'}, {'eggs': '1', ' bread': '3', ' milk': '3'}]
print(total_eggs)
# 8
Another method would be to use defaultdict here to setup some dictionaries that will store the information from the text file in a organized fashion where you can access it and manipulate easier down the road
from collections import defaultdict
with open('text.txt') as f:
content = [line.strip('\n ') for line in f]
dd = defaultdict()
content = [i.split(',') for i in content]
for i, v in enumerate(content):
dd[i] = dict([j.split('=') for j in v])
print(dd)
# {0: {'eggs': '2', ' bread': '1', ' milk': '4'}, 1: {'eggs': '5', ' bread': '2', ' milk': '2'}, 2: {'eggs': '1', ' bread': '3', ' milk': '3'}})
print(sum([int(dd[k]['eggs']) for k in dd]))
# 8
Working method with keys
holding no value:
with open('text.txt') as f:
content = [line.strip('\n ') for line in f]
content = [i.split(',') for i in content]
lista = []
for i in content:
for j in i:
if len(j.split('=')) > 1:
lista.append({j.split('=')[0]: j.split('=')[1]})
else:
lista.append({j: 0})
total_eggs = sum([int(v) for i in lista for k, v in i.items() if 'eggs' in k])
Upvotes: 1
Reputation: 107040
You can read the file into a dict of lists with dict comprehension:
{g[0][0]: [v for _, v in g] for g in zip(*([t.split('=') for t in l.split(', ')] for l in f))}
so that given your sample input from the file object f
, the above would return:
{'eggs': ['2', '5', '1'], 'bread': ['1', '2', '3'], 'milk': ['4 ', '2', '3']}
Upvotes: 0