vine_J
vine_J

Reputation: 153

Keep duplicate values - python dictionary

I am new to Python, couldn't find a way around this.

I am trying to print pair ['11','2'] twice in the output dictionary (as in the input string) but its somewhere getting dedup'd. Can someone please help?

import operator
a="2000 10003 1234000 44444444 9999 11 11 22 123"
a = a.split()
if len(a)<1:
    print("List is empty")
else:
    thisdict={}
    print (a)
    arr = []
    m=-1
    for i in range(0,len(a)):
        m+=1
        k=0
        for j in list(a[m]):
                k = k + int(j)
        thisdict[a[m]] = k
        i=i+1
    sorted_dict = sorted(thisdict.items(), key=lambda kv: kv[1])
    print(sorted_dict)

Output:

['2000', '10003', '1234000', '44444444', '9999', '11', '11', '22', '123']

[('2000', 2), ('11', 2), ('10003', 4), ('22', 4), ('123', 6), ('1234000', 10), ('44444444', 32), ('9999', 36)]

Expected Output:

['2000', '10003', '1234000', '44444444', '9999', '11', '11', '22', '123']

[('2000', 2), ('11', 2), ('11', 2), ('10003', 4), ('22', 4), ('123', 6), ('1234000', 10), ('44444444', 32), ('9999', 36)]

Upvotes: 0

Views: 550

Answers (1)

Ofer Sadan
Ofer Sadan

Reputation: 11922

Python dictionaries cannot contain 2 identical objects as keys. (Or, more accurately, objects that share the same hash).

Since your output is a list of tuples anyway, why not go there in the first place (instead of through a dictionary that can't do that)?

Here's what that would look like:

a = "2000 10003 1234000 44444444 9999 11 11 22 123"
result = [(value, sum(int(char) for char in value)) for value in a.split()]
sorted_result = sorted(result, key=lambda x: (x[1], x[0]))
print(sorted_result)

Output:

[('11', 2), ('11', 2), ('2000', 2), ('10003', 4), ('22', 4), ('123', 6), ('1234000', 10), ('44444444', 32), ('9999', 36)]

Upvotes: 2

Related Questions