Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Reciveing 'none' when trying to add the string of an exception to a dictionary

So I’m trying to get this working, where I remove the week’s stats (weeklydict) from this second’s stats (instantdict) so I have an accurate weekly progress for all keys of instantdict (keys being members). It works fine and dandy, but when a new member joins (adding to the keys in instantdict), shit hits the fan, so I use try/except, and attempt to add the missing member to weeklydict too, except when I do that using except keyerror as e and str(e), I’m given a ‘none’ value. Any idea on what to do?

Code:

for member, wins in instantDict.items():
try:
    instantDict[member] = instantDict[member] - weeklyDict[member]
except KeyError as e:
    weeklyDict[str(e)] = instantDict.get(str(e))    #error occurs here
    instantDict[member] = instantDict[member] - weeklyDict[member]  #thus fucking this up

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Based on my testing, str(e) returns a string as such:
"'test'"
The value is a string displaying a string, so .get() is not finding the value. Try something like:

for member, wins in instantDict.items():
    try:
        instantDict[member] = instantDict[member] - weeklyDict[member]
    except KeyError as e:
        weeklyDict[str(e).strip("'")] = instantDict.get(str(e).strip("'"))
        instantDict[member] = instantDict[member] - weeklyDict[member]

That should take the extra string characters off of the keyword, and allow .get() to actually find the value.

Alternatively, if you know that it errored because you know that member is not in the dictionary, why pull the exact same variable from the exception when you could just use member again?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading