python - Imported two separate text files to organize into dict, does not reading 2nd file properly and get a KeyError for any data in the 2nd file -


i trying add branded , generic cereals under 1 dictionary , separate key named main_brand holding boolean value.

this in file mainbrands.txt

# brand name,company,founded  apple jacks,kellogg's,1965 cheerios,general mills,1941 ... 

this in file genericbrands.txt

apple jills,afirm,2011 cheery oats,bfirm,2015 ... 

this under main.py

import os branded = open(os.path.join(os.getcwd(), 'mainbrands.txt'), 'r').readlines() generic= open(os.path.join(os.getcwd(), 'genericbrands.txt'), 'r').readlines()  history = {'founded': {}, 'main_brand': {}}  x in range(0, len(branded)):     data = branded[x].strip().split(',')     history[data[0]] = {'company': data[1], 'founded': data[2], 'main_brand': true}  y in range(0, len(generic)):     data = generic[y].strip().split(',')     history[data[0]] = {'company': data[1], 'founded': data[2], 'main_brand': false}  def history_check(key):     key_list = list(history.keys())     in range(0, len(key_list)):         if key_list[i] in key:             return history[key_list[i]] 

i keep main brands , generic brands 2 separate lists rather combine 2 lists , add on additional comma deliminator become less readable (this simplified toy example)

some sample outputs are:

>>print(history_check('cherrios')['company']) general mills  >>print(history_check('apple jacks')['founded']) 1965  >>print(history_check('cheery oats')['founded']) keyerror: 'cheery oats' 

why of keys genericbrands.txt not being read?

the keys genericbrands.txt getting put history dictionary. take yourself...

print(history) 

also notice have dead keys in there 'company': {}. believe @aaron correct go history = {}

i think looking history_check do...

def history_check(key):     return history[key]  print(history_check('apple jacks')['founded']) print(history_check('cheery oats')['company']) 

edit: if you're getting key error double check example. copied , made changes above output of 1965 , bfirm


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -