0

New user in python.

I'm trying to make MX records readable by checking a dictionary.

This only returns the "else", but I can't find out why.

import re

mx_dict = {
    "l.google.com": "Google",
    "protection.outlook.com": "Outlook",
    "one.com": "One"
}

def mx_check(mx_record):
    for key, value in mx_dict.items():
        if re.search(key, mx_record):
            return value
        else:
            return mx_record

print(mx_check('aspmx.l.google.com.'))

Solution found, thank you @khelwood

import re
mx_class = {
    "l.google.com": "Google",
    "one.com": "One",
    "domenehost.no": "Domenehost"
}

def mx_check(mx_record):
    for key, value in mx_class.items():
        if re.search(key, mx_record):
            mx_record = value
    
    return mx_record

print(mx_check('mx2.pub.mailpod3-cph3.one.com.'))
Kaaven
  • 1
  • 3
  • 1
    Your loop always returns on the first iteration. If the first key it checks isn't found, it immediately returns `mx_record` and skips the rest of the loop. Move the `return mx_record` to after the loop. – khelwood Apr 22 '21 at 19:22
  • Why not use `key in mx_record`? – Altareos Apr 22 '21 at 19:22
  • `.` has special meaning in regular expressions. You should escape them if you want to match them literally. Otherwise, `one.com` will match `onexcom` – Barmar Apr 22 '21 at 19:28
  • @Barmar Your second comment is exactly why I asked why OP is using regexes :) – Altareos Apr 22 '21 at 19:50
  • @Barmar `'one.com' in 'mx2.pub.mailpod3-cph3.one.com.' == True` – Altareos Apr 22 '21 at 19:53
  • @Altareos I misread your comment. I thought you were doing `mx_record in mx_dict` – Barmar Apr 22 '21 at 19:55

0 Answers0