Issue
The problem is about to print the report of users and their current status of the employees doing login or logout in several machines of a company.
class Event: def __init__(self, event_date, event_type, machine_name, user): self.date = event_date self.type = event_type self.machine = machine_name self.user = user def get_event_date(event): return event.date def current_users(events): events.sort(key=get_event_date) machines = {} for event in events: if event.machine not in machines: machines[event.machine] = set() if event.type == "login": machines[event.machine].add(event.user) elif event.type == "logout": machines[event.machine].remove(event.user) return machines def generate_report(machines): for machine, users in machines.items(): if len(users) > 0: user_list = ", ".join(users) print("{}: {}".format(machine, user_list)) events = [ Event('2020-01-21 12:45:56', 'login', 'myworkstation.local', 'jordan'), Event('2020-01-22 15:53:42', 'logout', 'webserver.local', 'jordan'), Event('2020-01-21 18:53:21', 'login', 'webserver.local', 'lane'), Event('2020-01-22 10:25:34', 'logout', 'myworkstation.local', 'jordan'), Event('2020-01-21 08:20:01', 'login', 'webserver.local', 'jordan'), Event('2020-01-23 11:24:35', 'logout', 'mailserver.local', 'chris'), ] users = current_users(events) print(users)
I have successfully compiled and got the output on my pycharm :
{'webserver.local': {'jordan'}}
Process finished with exit code 0
But I got an error on jupyter notebook.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-11-46e68509ab0d> in <module>
----> 1 users = current_users(events)
2 print(users)
<ipython-input-8-5fb178c90d75> in current_users(events)
11 machines[event.machine].add(event.user)
12 elif event.type == "logout":
---> 13 machines[event.machine].remove(event.user)
14 return machines
15
KeyError: 'chris'
I know it's because we have a user in our events list that was logged out of a machine he was not logged into.
But my question is, what does such 'chris' keyerror means or why my pycharm compiled showing the result where jupyter notebook did not?
Solution
In your code, for user chris
there is no entry for login
. So, in current_users()
function when it encounters the entry for chris
, it is trying to remove that element from the set.
But the machines['mailserver.local']
do not have an entry for chris
in that set. As there is no such entry, you get the mentioned error.
One simple solution is to check if the entry is present in the set before trying to remove it. Like -
elif event.type == "logout" and event.user in machines[event.machine]:
machines[event.machine].remove(event.user)
Answered By - kuro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.