try and except not working - python

Hi i have the following code. When i run getDetails function the try:
does work but the exception is not displaying properly.
data_dict = {}
dict_list = []
def createNameDict(filename):
path = "C:\Users\user\Desktop"
basename = "ParkingData_Part2.txt"
filename = path + "//" + basename
file = open(filename)
contents = file.read()
print contents,"\n"
data_list = [lines.split(",") for lines in contents.split("\n")]
for line in data_list:
regNumber = line[0]
details = (line[1],line[2],line[3])
data_dict[regNumber] = details
print data_dict,"\n"
print data_dict.items(),"\n"
def getDetails(regNumber):
#if regNumber in data_dict:
try:
if regNumber in data_dict:
print data_dict[regNumber]
#print data_dict.get(regNumber)
except:
printNow(regNumber, "not in dictionary")
return
def addRegistration(regNumber, details):
try:
data_dict[regNumber] = details
except:
print regNumber, "Key Already exist"
#data_dict.update({regNumber:(details)})
return data_dict
The output I have is:
======= Loading Progam =======
>>> createNameDict("C:\Users\user\Desktop//ParkingData_Part2.txt")
EDF768, Bill Meyer, 2456, Vet_Parking
TY5678, Jane Miller, 8987, AgHort_Parking
GEF123, Jill Black, 3456, Creche_Parking
ABC234, Fred Greenside, 2345, AgHort_Parking
GH7682, Clara Hill, 7689, AgHort_Parking
JU9807, Jacky Blair, 7867, Vet_Parking
KLOI98, Martha Miller, 4563, Vet_Parking
ADF645, Cloe Freckle, 6789, Vet_Parking
DF7800, Jacko Frizzle, 4532, Creche_Parking
WER546, Olga Grey, 9898, Creche_Parking
HUY768, Wilbur Matty, 8912, Creche_Parking
{'HUY768': (' Wilbur Matty', ' 8912', ' Creche_Parking'), 'GH7682': (' Clara Hill', ' 7689', ' AgHort_Parking'), 'GEF123': (' Jill Black', ' 3456', ' Creche_Parking'), 'WER546': (' Olga Grey', ' 9898', ' Creche_Parking'), 'TY5678': (' Jane Miller', ' 8987', ' AgHort_Parking'), 'ABC234': (' Fred Greenside', ' 2345', ' AgHort_Parking'), 'KLOI98': (' Martha Miller', ' 4563', ' Vet_Parking'), 'EDF768': (' Bill Meyer', ' 2456', ' Vet_Parking'), 'JU9807': (' Jacky Blair', ' 7867', ' Vet_Parking'), 'DF7800': (' Jacko Frizzle', ' 4532', ' Creche_Parking'), 'ADF645': (' Cloe Freckle', ' 6789', ' Vet_Parking')}
[('HUY768', (' Wilbur Matty', ' 8912', ' Creche_Parking')), ('GH7682', (' Clara Hill', ' 7689', ' AgHort_Parking')), ('GEF123', (' Jill Black', ' 3456', ' Creche_Parking')), ('WER546', (' Olga Grey', ' 9898', ' Creche_Parking')), ('TY5678', (' Jane Miller', ' 8987', ' AgHort_Parking')), ('ABC234', (' Fred Greenside', ' 2345', ' AgHort_Parking')), ('KLOI98', (' Martha Miller', ' 4563', ' Vet_Parking')), ('EDF768', (' Bill Meyer', ' 2456', ' Vet_Parking')), ('JU9807', (' Jacky Blair', ' 7867', ' Vet_Parking')), ('DF7800', (' Jacko Frizzle', ' 4532', ' Creche_Parking')), ('ADF645', (' Cloe Freckle', ' 6789', ' Vet_Parking'))]
>>> getDetails("GFT245")
>>> getDetails("HUY768")
(' Wilbur Matty', ' 8912', ' Creche_Parking')
>>> getDetails("JU9807")
(' Jacky Blair', ' 7867', ' Vet_Parking')
>>> getDetails("GH7682")
(' Clara Hill', ' 7689', ' AgHort_Parking')
>>>
If GFT245 is not in dictionary it should show
GFT245 not in dictionary
but its not coming that way when i execute the program

The problem is located here:
if regNumber in data_dict:
print data_dict[regNumber]
As you are asking whether regNumber is or is not present in the dictionary the exception will never be raised due to the fact that in case regNumber is not present you will not try to index it, thus not raising the KeyError exception.
If you want the exception to be raised then just do:
print data_dict[regNumber]

In your getDetails function the except section will never fire as you explicitly check if the key is in the dictionary before you access it, you would want to re-write it either as
if key in dict:
# The key exists and do something
else:
# The key doesn't exist, notify the user
or
try:
print dict[key]
except KeyError:
# The key doesn't exist, notify the user
I prefer the style of the first as exceptions are expensive, of course if you know that you will only have a small number of keys that do not exist in the dictionary and would cause the exception, then you could optimize the second way.
And your addRegistration function should be re-written to test if the key exists already and notify the user, else add the data, as it will not warn you or raise an exception if the key already exists, it will just update/replace the data for that key.

if regNumber in data_dict:
print data_dict[regNumber]
You have a conditional before accessing data_dict. If regNumber is not in dict then it will not try to access it. Hence no exception is thrown.

def getDetails(regNumber):
#if regNumber in data_dict:
try:
if regNumber in data_dict:
print data_dict[regNumber]
#print data_dict.get(regNumber)
except:
printNow(regNumber, "not in dictionary")
return
Nothing in that try block is actually failing.
Why? Because of the if regNumber in data_dict test. If the code is not in the dictionary, it will never attempt to look it up.
Perhaps you meant something like:
def getDetails(regNumber):
if regNumber in data_dict:
print data_dict[regNumber]
else:
printNow(regNumber, "not in dictionary")

The problem is
try:
if regNumber in data_dict:
print data_dict[regNumber]
#print data_dict.get(regNumber)
except:
printNow(regNumber, "not in dictionary")
if regNumber is not in data_dict, no exception occures. Change it to:
try:
print data_dict[regNumber]
except:
printNow(regNumber, "not in dictionary")

Related

Python 3: Making a new line in a variable

I'm currently trying to make an ASCII map via python using segments of walls. I got it to work in print() but I'm a bit new and don't know how to store it to a variable.
If I invoke the variable, it prints the list with no line breaks. If I assign a variable to a print, it works, but prints it all first before I want it to.
Any solutions? Can I format the initial a1_map list to create the new lines?
Here's what I have:
north_exit = ' ___| |___'
north_no_exit = ' ___________'
south_exit = ' ```| |``` '
mid_no_exit = '| |'
top_WandE_exit = '\u2143 L'
top_W_exit = '\u2143 |'
top_E_exit = '| L'
mid_WandE_exit = ' (\u00B0.\u00B0) '
mid_W_exit =' (\u00B0.\u00B0) |'
mid_E_exit ='| (\u00B0.\u00B0) '
lower_W_exit = '\u02E5 |'
lower_WandE_exit = 'T T'
lower_E_exit = '| T'
current_room = 'the crew quarters'
a1_map = print(north_no_exit,'\n' + top_E_exit,'\n' + mid_E_exit,'\n' + lower_E_exit, '\n' +south_exit, '\n'+ 'You are in',current_room+'.')
I could just type:
print(north_no_exit,'\n' + top_E_exit,'\n' + mid_E_exit,'\n' + lower_E_exit, '\n' +south_exit, '\n'+ 'You are in',current_room+'.')
each time. However I want to format it so I can just type:
print(a1_map)
As an example, the list output without print() looks like:
(' ___________', '\n| L', '\n| (°.°) ', '\n| T', '\n | | ', '\nYou are in', 'the crew quarters.')
I would like it to look like (as an example):
___________
| L
| (°.°)
| T
```| |```
(EDIT: Sorry, trying to make it look like a box but I cant even do it on here!)
So, I feel dumb.
Formatting it and then using a loop seemed to work
a1_map = [north_no_exit, top_E_exit, mid_E_exit, lower_E_exit, south_exit]
for segment in a1_map:
print(segment)
You can simply use + to join strings or string join() method to join them with a separator string.
You can also make a dictionary or a list to help you manage them and iterate them
I think you can use Python's f-string.
north_exit = ' ___| |___'
north_no_exit = ' ___________'
south_exit = ' ```| |``` '
mid_no_exit = '| |'
top_WandE_exit = '\u2143 L'
top_W_exit = '\u2143 |'
top_E_exit = '| L'
mid_WandE_exit = ' (\u00B0.\u00B0) '
mid_W_exit =' (\u00B0.\u00B0) |'
mid_E_exit ='| (\u00B0.\u00B0) '
lower_W_exit = '\u02E5 |'
lower_WandE_exit = 'T T'
lower_E_exit = '| T'
current_room = 'the crew quarters'
a1_map = f"{north_no_exit}\n{top_E_exit}\n{mid_E_exit}\n{lower_E_exit}\n{south_exit}\n"
message = "You are in',current_room."
print(a1_map+message)

how to pass variable instead of number in sendcommand in autocad python

how to pass variable instead of number in sendcommand
acad.doc.SendCommand('QLEADER ' '0,500' '\n' '200,1000 ''\n' '500 ' 'ABC \n' '\n' )
this works but
a=0
b=500
acad.doc.SendCommand('QLEADER ' 'a,b ' '\n' '200,1000 ''\n' '500 ' 'ABC \n' '\n' )
but this doesn't work
Try using f-String:
a=0
b=500
acad.doc.SendCommand('QLEADER ' f'{a},{b} ' '\n' '200,1000 ''\n' '500 ' 'ABC \n' '\n' )
Hope it helps.

Need help joining dictionary items and remove newlines and multiple spaces and special characters

Dictionary with 2 urls and their text: Need to get rid of all multiple spaces, special characters and new lines
{'https://firsturl.com': ['\n\n',
'\n ',
'\n \n \n ',
'\n \n ',
'\n \n ',
'\n\n ',
'\n',
'\n',
'\n ',
'\n ',
'Home | Sam ModelInc',
'\n \n\n\n',
'\n\n\n\n',
'\n\n',
'\n \n\n\n\n\n\n\n\n\n \n \n',
'\n',
'\n',
'\n',
'\n',
'\n ',
'\n ',
'Skip to main content'],'https://secondurl.com#main-content': ['\n\n',
'\n ',
'\n \n \n ',
'\n \n ',
'\n \n ',
'\n\n ',
'\n',
'\n',
'\n ',
'\n ',
'Home | Going to start inc',
'\n \n\n\n',
'\n\n\n\n',
'\n\n',
'\n \n\n\n\n\n\n\n\n\n \n \n',
'\n',
'\n',
'\n',
'\n',
'\n ',
'\n ',
'Skip to main content',
'\n ',
'\n \n',
'\n\n ',
'\n\n ',
'\n \n \n \n \n ',
'\n\n ',
'\n ',
'\n\n \n ',
'\n ',
'\n\n \n ',
'\n ',
'Brands',
'\n',
'About Us',
'\n',
'Syndication',
'\n',
'Direct Response']}
Expected Output:
{'https://firsturl.com': ['home sam modelInc skip to main content'], https://secondurl.com#main-content': ['home going to start inc skip to main content brands about us syndication direct response]}
Help would be much appreciated
So let's try to walk through this instead of just throwing some code at you.
The first element we want to get rid of is the newline. So we could start with something like:
ex_dict = {"a": ["\n\n", "\n"]}
for x in ex_dict:
new_list = [e for e in ex_dict[x] if "\n" not in e]
ex_dict[x] = new_list
If you run that, you'll see that we now filter out all new lines.
Now we have the following cases:
Home | Sam ModelInc
Skip to main content
Home | Going to start inc
Brands
About Us
Syndication
Direct Response
According to your expected output, you want to lowercase all words and remove non-alphabet characters.
Did a little research for how to do that.
In code, that looks like:
import re
regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces
ex_dict = {"a": ["\n\n", "\n"]}
for x in ex_dict:
new_list = [e for e in ex_dict[x] if "\n" not in e]
"""
>>> regex.sub("", "Home | Sam ModelInc")
'Home Sam ModelInc'
"""
new_list = [regex.sub("", e) for e in new_list]
ex_dict[x] = new_list
so now our final new_list looks something like: ['Home Sam ModelInc', 'Skip to main content']
Next we want to lowercase everything.
import re
regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces
ex_dict = {"a": ["\n\n", "\n"]}
for x in ex_dict:
new_list = [e for e in ex_dict[x] if "\n" not in e]
"""
>>> regex.sub("", "Home | Sam ModelInc")
'Home Sam ModelInc'
"""
new_list = [regex.sub("", e) for e in new_list]
new_list = [e.lower() for e in new_list]
ex_dict[x] = new_list
and lastly we want to combine everything with only one space between each word.
import re
regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces
ex_dict = {"a": ["\n\n", "\n"]}
for x in ex_dict:
new_list = [e for e in ex_dict[x] if "\n" not in e]
"""
>>> regex.sub("", "Home | Sam ModelInc")
'Home Sam ModelInc'
"""
new_list = [regex.sub("", e) for e in new_list]
new_list = [e.lower() for e in new_list]
new_list = [" ".join((" ".join(new_list)).split())]
ex_dict[x] = new_list

How do I make a dictionary that stores data as a list? [More complicated]

I have a problem with dictionaries that I need help with.
Here is an excerpt from weather.txt:
Hail : 1 : xxx
Hail : 2 : xxx
Hail : 3 : xxx
Rain : 1 : xxx
Rain : 2 : xxx
Rain : 3 : xxx
The first value is the weather, the second value is the intensity and the third is just a short description.
Here is an excerpt from my game:
weather = open("weather.txt")
weather_list = {}
for line in weather:
line = line.rstrip().split(":")
weather_list[line[0][int(line[1]) -1]] = (line[0], line[1], line[2])
for key, value in weather_list.items():
print key, ":", value
That prints this:
a : ('Rain ', ' 2 ', ' xxx')
i : ('Rain ', ' 3 ', ' xxx')
H : ('Hail ', ' 1 ', ' xxx')
R : ('Rain ', ' 1 ', ' xxx')
But I want it to print this:
'Rain': [('Rain ', ' 1 ', ' xxx'), ('Rain ', ' 2 ', ' xxx'), i : ('Rain ', ' 3 ', ' xxx')]
'Hail': etc...
I know my issue is with the syntax "weather_list[line[0][int(line[1]) -1]]". What I want it to do is have 1 key for each weather, and each value to be a tuple or list containing all the values for that weather, sorted by intensity, (intensity 1, intensity 2, intensity 3).
Any and all help is appreciated. Hope I explained it better this time.
Solution
This works:
weather = {}
with open('weather.txt') as fobj:
for line in fobj:
data = line.strip().split(':')
weather.setdefault(data[0], []).append(tuple(data))
weather = {key: sorted(value, key=lambda x: x[1]) for key, value in weather.items()}
The result looks like this:
>>> weather
{'Hail ': [('Hail ', ' 1 ', ' xxx'),
('Hail ', ' 2 ', ' xxx'),
('Hail ', ' 3 ', ' xxx')],
'Rain ': [('Rain ', ' 1 ', ' xxx'),
('Rain ', ' 2 ', ' xxx'),
('Rain ', ' 3 ', ' xxx')]}
Variation
The above solution has, as requested, redundant information for Rain and Hail. This version does not store them as first element in tuple but only as key in the dictionary:
weather = {}
with open('weather.txt') as fobj:
for line in fobj:
data = line.strip().split(':')
weather.setdefault(data[0], []).append(tuple(data[1:]))
weather = {key: sorted(value) for key, value in weather.items()}
The sorting is simpler and the result looks like this:
>>> weather
{'Hail ': [(' 1 ', ' xxx'), (' 2 ', ' xxx'), (' 3 ', ' xxx')],
'Rain ': [(' 1 ', ' xxx'), (' 2 ', ' xxx'), (' 3 ', ' xxx')]}

Looping through dictionary and getting keys [duplicate]

This question already has answers here:
Iterating over dictionaries using 'for' loops
(15 answers)
Closed 7 years ago.
I'm trying to get the names in a dictionary and their corresponding key values.
Sorry if this has already been asked. This code is not working because I suck at programming and just starting. Please tell me what's wrong with it.
theBoard = {'top-L': ' ',
'top-M': ' ',
'top-R': ' ',
'mid-L': ' ',
'mid-M': ' ',
'mid-R': ' ',
'low-L': ' ',
'low-M': ' ',
'low-R': ' '
'Check for closed moves'
def openMoves:
for i in theBoard:
if theBoard[i] == ' ':
print "the move %s is open" % theBoard[i]
else:
print "the move %s is taken" % theBoard[i]
print openMoves()
theBoard = {'top-L': ' ',
'top-M': ' ',
'top-R': ' ',
'mid-L': ' ',
'mid-M': ' ',
'mid-R': ' ',
'low-L': ' ',
'low-M': ' ',
'low-R': ' '
} # <--- Close your dictionary
# <--- remove random string 'Check for c...'
def openMoves(): # <--- add parenthesis to function
for k, v in theBoard.items(): # <--- loop over the key, value pairs
if v == ' ':
print "the move %s is open" % k
else:
print "the move %s is taken" % k
openMoves() # <-- remove the print statement
theBoard = {'top-L': ' ',
'top-M': ' ',
'top-R': ' ',
'mid-L': ' ',
'mid-M': ' ',
'mid-R': ' ',
'low-L': ' ',
'low-M': ' ',
'low-R': ' '}
def openMoves():
for k,v in theBoard.items():
if v == ' ':
print "the move %s is open" %k
else:
print "the move %s is taken" %k
I think your tabbing is off too...

Categories

Resources