Skip to content
Advertisement

Exchange a key with one of its values–python dictionary—-another question

I have the following example, I have seen the execution flow of the piece of code, and I know it has a problem thus I cannot get the desired result from the code. However, I have tried many ways and still do not know, how can I get the desired result.

Code:

dict1 = {10: [22], 40: [50, 20, 60]}
new_dict = {}
for k, v in dict1.items():
    for each_v in v:
        if each_v < k:
            v.remove(each_v)
            # temp_v = v.copy()
            # temp_v.remove(each_v)
            new_dict[each_v] = [k] + v
            # print(temp_v)
            # print(v)
    else:
        new_dict[k] = v
print(new_dict)

Current output:

{10: [22], 20: [40, 50, 60], 40: [50, 60]}

Desired output:

{10: [22], 20: [40, 50, 60]}
*keep the original order*

What I only want, is to exchange the key and one of its values IF the key is bigger than this value. I do not want to add more item to the dictionary. Also

If any of you has a hint, please do comment, thanks in advance!

Advertisement

Answer

My approach: iterate over a copy of all key, value pairs. If a values list has a value that is smaller than the key, we delete the key. Then we replace the smallest value in the list with the key, and use that value as the new key.

dict1 = {10: [22], 40: [50, 20, 60]}
for k, v in list(dict1.items()): # using list() to copy the dict's items
                                 # since we are going to delete a key
    min_v = min(v)
    if min_v < k:
        del dict1[k]
        min_v_index = v.index(min_v)
        v[min_v_index] = k
        dict1[min_v] = sorted(v)

print(dict1)

outputs

{10: [22], 20: [40, 50, 60]}

A CAVEAT

you will have a problem if a candidate key is already a key in the original dict. Consider having {10: [22], 25: [10]}. This will attempt to create a dictionary with duplicated 10 keys. The above code will output {10: [25]}.

The solution is to check if the new key is already present in the original dict, and if it does, just append the value to that key’s list, then sort it. I will leave the implementation as an exercise for the reader.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement