-1

My script reads from a file (syslog.txt) with the log history of users, parses through each log entry in the file and creates 2 dictionaries (error, per_user) to display how many instances of a given error has occured and the amount of INFO or ERROR instances each user has got. All OK until here. Code seems to work fine. The problem is that the output are 2 lists and not 2 dictionaries. I cannot figure out why. Thank you very much in advance.

Here is the script:

import re
import operator

per_user = {}
error = {}

with open("syslog.txt") as f:
    content = f.readlines()
    for i in content:
        if "ERROR" in i:
            result_error = re.search(r"ERROR ([\w\' ]+) [^\w]",i)
            if not result_error.group(1) in error:
                error[result_error.group(1)] = 1
            else:
                error[result_error.group(1)] += 1

        result_user = re.search(r"(INFO|ERROR).*\(([\w\.]+)\)",i)  
        if not result_user.group(2) in per_user:
            per_user[result_user.group(2)] = dict()
        if not result_user.group(1) in per_user[result_user.group(2)]:
            per_user[result_user.group(2)][result_user.group(1)] = 1
        else:
            per_user[result_user.group(2)][result_user.group(1)] += 1


error = sorted(error.items(), key=operator.itemgetter(1), reverse=True) 
per_user = sorted(per_user.items(), key=operator.itemgetter(0))

print(type(error))
print(type(per_user))

Below is the output:

<class 'list'>

<class 'list'>
Pacool1234
  • 47
  • 4

2 Answers2

1

From the documentation for sorted:

Return a new sorted list from the items in iterable.

If sorted was not returning a list, that would be unexpected.

1

Note:

sorted(iterable): Returns a new list containing all the items from the iterable

If you want the dictionary,

Try this:

error = dict(error)
per_user = dict(per_user)
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53