dPdms dPdms - 2 months ago 6
Python Question

python dictionary (unordered selections key)

I have a question about dic.has_key

my code is

def insertToDic(dic,comSick):
for datum in comSick :
if dic.has_key(datum):
else :
dic[datum] =1

if comSick is


dic will be

dic = {(A,B) : 1, (A,C) : 1, (B,A) : 1}

but what I want is unordered key (which means (A,B) = (B,A))

dic = {(A,B) : 2, (A,C) : 1} <-- this is what I want

what should I do?


Try this:

def insertToDic(dic,comSick):
    for datum in comSick :
        sorted_datum = tuple(sorted(datum))
        dic[sorted_datum] = dic.get(sorted_datum, 0) + 1

comSick=[('A', 'B'), ('A', 'C'), ('B', 'A')]

dic = {}
insertToDic(dic, comSick)

I made some changes. I sorted the datum before updating the dictionary. This ensures that one of (A,B) and (B,A) will be changed to the other. It is not clear what A and B are, so B may be lower than A. Did you mean the strings 'A' and 'B'? That's what I used.

I also changed how you increment the value. The get() method will return the current value if it exists or the given default value if it doesn't--in this case, zero.

Also note that the final dictionary has no inherent order, so you may get the answer {('A', 'C'): 1, ('A', 'B'): 2}, which is what I got in my Python 3.5.2 in Anaconda.