python: Dictionary Operation, KeyError: '0' - python

I want to extract information from a text file and store the data in a directionary. The file records semicolon seperated values. That is, it records one property in one line, and the key and the value are seperated by a semicolon followed by a white space.
def info_file_parser(info_file):
f=open(info_file,'rb')
info={}
for line in f:
line=line.rstrip()
mlist=line.split(": ")
if len(mlist)==2:
info[mlist[0]]=info[mlist[1]]
if __name__='__main__':
fname="/Users/me/info.txt"
info_file_parser(fname)
KeyError: '0'. What's wrong with that? Why can't I create keys by assignment?

You are trying to set a key in your dictionary with a key that doesn't exist.
In the if statement of your function, shouldn't it be:
if len(mlist)==2:
info[mlist[0]]=mlist[1]

this line:
info[mlist[0]]=info[mlist[1]]
tries to store value from info dictonary with key mlist[1] and try this:
info[mlist[0]]=mlist[1]

Related

Check if multiple dictionary keys are located in a string

Imagine having a txt file with like
5843092xxx289421xxx832175xxx...
You have a dictionary with keys correspoding to letters
A am trying to search for each key within the string to output a message.
decoder = {5843092:'a', 289421:'b'}
with open( "code.txt","r") as fileTxt:
fileTxt = fileTxt.readlines()
b = []
for key in decoder.keys():
if key in fileTxt:
b.append(decoder[key])
print(b)
this is what I have I feel like im on the right track but I am missing how to do each iteration maybe?
the goal output in this i.e. would be either a list or string of ab...
There are two problems here:
You have a list of strings, and you're treating it as if it's one string.
You're building your output based on the order the keys appear in the decoder dictionary, rather than the order they appear in the input text. That means the message will be all scrambled.
If the input text actually separates each key with a fixed string like xxx, the straightforward solution is to split on that string:
for line in fileTxt:
print(' '.join(decoder.get(int(key), '?') for key in line.split('xxx')))

How to read one character from a file as a key into a dictionary, then make the next n characters its value?

Lets say we have a .txt file like so (all on one line):
A2.)43#|#C3::#
So we want "A" as key for the value ".)" and "4" as key for the value "#|#" etc.. The number after the key tells us how many characters to read as the value, and the character after is the key for the next item in the dictionary.
The thing I'm struggling with is writing the loop. I'm thinking that we might want to iterate over the length of the file using a for loop. But I don't really know how to proceed.
This worked for me
stringText = "A2.)43#|#C3::#"
i=0
myDictionary = {}
while True:
try:
#First we grab the key character using i
keyCharacter = stringText[i]
#Then we grab the next character which will tell us how many characters they value will have
# We also convert it to integer for future use
valueLength = int(stringText[i+1])
#Then we grab the value by slicing the string
valueCharacters = stringText[i+2:i+2+valueLength]
#We add this to the dictionary
myDictionary[keyCharacter] = valueCharacters
#We update i to continue where we left off
i = i+2+valueLength
except IndexError:
break
print myDictionary
Instead of the "try and except" you could also see how long that string is and do and if statement to break the loop when i is bigger than the length of the string.

python: Search for a word and read the value from a file

I would like to populate a dictionary by fetching the values associated with a tag.
For example: if I have these variables stored in the file as
NUM 0 OPERATION add DATA [0x1, 0x2]
How can I extract the values of NUM, OPERATION and DATA if the order of the tag's is not fixed?
Thanks in advance.
If you can assure that the operation never contains a space you can do something like this with the built-in method str.split:
>>> line.split(' ', 5)[1::2]
['0', 'add', '[0x1, 0x2]']
It splits the line in a list of parts that are separated by and then returns every second entry of this list starting with the second.

Searching in a .txt file (JSON format) for a particular string and then printing a specific key

I have to take input from the user in the form of strings and then have to search for it in a .txt file which is in JSON format. If the text matches, X has to be done otherwise Y. For example if the user enters 'mac' my code should display the complete name(s) of the terms which contains the search term 'mac'.
My JSON file has currently Big Mac as an item and when I search for 'mac' it shows nothing, whereas, it has to display me (0 Big Mac). 0 is the index number which is also required.
if option == 's':
if 'name' in open('data.txt').read():
sea = input ("Type a menu item name to search for: ")
with open ('data.txt', 'r') as data_file:
data = json.load(data_file)
for line in data:
if sea in line:
print (data[index]['name'])
else:
print ('No such item exist')
else:
print ("The list is empty")
main()
I have applied a number of solutions but none works.
See How to search if dictionary value contains certain string with Python.
Since you know you are looking for the string within the value stored against the 'name' key, you can just change:
if sea in line
to:
if sea in line['name']
(or if sea in line.get('name') if there is a risk that one of your dictionaries might not have a 'name' key).
However, you're attempting to use index without having set that up anywhere. If you need to keep track of where you are in the list, you'd be better off using enumerate:
for index, line in enumerate(data):
if sea.lower() in line['name'].lower():
print ((index, line['name']))
If you want 'm' to match 'Big Mac' then you will need to do case-insensitive matching ('m' is not the same as 'M'). See edit above, which converts all strings to lower case before comparing.

Key:Value Pairs from txt file into a dictionary

I have a txt file with key value pairs. It can format (get, retrieve) the pairs from the file in multiple ways, for example:
as line separated strings with colons:
stringa1:stringa2
stringb1:stringb2
or as line separated strings with commas:
stringa1,stringa2
stringb1,stringb2
or as individuals lists of strings:
[stringa1,stringa2]
['stringa1','stringa2']
AND, I can assign each string to a variable with:
for string in list
splitstring=list.split(',')
for item in splitstring:
print (item)
>>>stringa1
>>>stringa2
But I can't figure out how to add those key:value pairs to a dictionary
d[splitstring[0]] = splitstring[1]
should work, where d is a dict. That's the easiest way of adding a key, value pair to a dictionary.
Another way is:
d.update({splitstring[0]: splitstring[1]})
Taking in mind that we are talking about pairs, then
this should work:
mydict = {}
for i in range(0,len(splitstring),2):
mydict[splitstring[i]] = splitstring[i+1]

Categories