Christian
Christian

Reputation: 1

dictionary with assigned value raises referenced before assignment error

I need to write a code that is supposed to put items from a dictionary in a list and sort them either after the key or the value. This is the code I came up with:

import copy
dict_ip_attempts = {"180.237.210.112": 9, "180.237.210.54": 5,
                     "180.237.210.13": 2, "180.237.210.30": 5}

d=copy.deepcopy(dict_ip_attempts)
ip_adress=[]
for key in dict_ip_attempts:
    var=key.split(".")
    ip_adress.append(int("".join(var)))

ip_adress.sort()

def sortip_adress():
    output=[0]*(len(ip_adress))
    for key in dict_ip_attempts:
        var=key.split(".")
        for i in range(len(ip_adress)):
            if int("".join(var)) == ip_adress[i]:
                output[i]=((key, dict_ip_attempts[key]))
    return output

def sortattempts():
    output=[]
    for key in dict_ip_attempts:
        if dict_ip_attempts[key]==min(dict_ip_attempts.values()):
            output.append((key, dict_ip_attempts[key]))
            dict_ip_attempts.pop(key)
    dict_ip_attempts=copy.deepcoy(d)
    return output

print("The dictionary sorted after the ip_adresses is:", sortip_adress())
print("The dictionary sorted after the attempts is:", sortattempts())

The function sortip_adress() works just fine, but the sortattempts() function doesn't. When python reaches line 30 it prints: UnboundLocalError: local variable 'dict_ip_attempts' referenced before assignment

line 30 is this one:

for key in dict_ip_attempts:

I don't understand why I get this error, since I defined dict_ip_attempts in line 2. Can someone explain it to me please?

Upvotes: 0

Views: 499

Answers (2)

Setop
Setop

Reputation: 2490

Add global dict_ip_attempts at the beginning of sortattempts function.

Edit: Basically, what you try to do is described here in a much more pythonic way.

Upvotes: 1

NendoTaka
NendoTaka

Reputation: 1224

Add global dict_ip_attempts as a line just under both of your function declarations since it is a global variable. Also popping a value from a dictionary in a for key in dictionary loop is a bad idea (as Wondercricket mentioned). It shouldn't be necessary, but if you need to empty the dictionary just do it after the loop is done with dict_ip_attempts = {}

Upvotes: 0

Related Questions