Search code examples
pythonsortingdictionaryswap

Switch two dictionaries in a nested dictionary


I'm trying to swap two dictionaries within another dictionary.
I would like to see the following result:

input: {10: {"name": "name_value1", "price1": "price_value1"}, 
        30: {"name": "name_value3", "price3": "price_value3"}, 
        20: {"name": "name_value2", "price2": "price_value2"}}
output:{10: {"name": "name_value1", "price1": "price_value1"}, 
        20: {"name": "name_value2", "price2": "price_value2"}, 
        30: {"name": "name_value3", "price3": "price_value3"}}

I have tried a lot of different things and sometimes the values were in the right order but the keys weren't updated. The code below is an example of this.

def my_sort(dct):
    index = 0
    key_list = list(dct.keys())
    while index < (len(dct) - 1):
        if key_list[index] > key_list[index + 1]:
            dct[key_list[index]], dct[key_list[index + 1]] = dct[key_list[index + 1]], dct[key_list[index]]
            key_list[index], key_list[index + 1] = key_list[index + 1], key_list[index]
            index = 0
        else:
            index += 1
            
    return dct

this code outputs the following:

{10: {"name": "name_value1", "price1": "price_value1"}, 
 30: {"name": "name_value2", "price2": "price_value2"}, 
 20: {"name": "name_value3", "price3": "price_value3"}}

NOTE: I can't use an external library / framework for this and I can't use functions like sorted().

All help and advice is welcome! Thank you in advance.


Solution

  • def sort_keys(keys_):
      for i in range(len(keys_)):
        for j in range(i, len(keys_)):
          if keys_[i]  > keys_[j]:
            keys_[i], keys_[j] = keys_[j], keys_[i]
      return keys_
    
    input = {10: {"name": "name_value1", "price1": "price_value1"}, 
            30: {"name": "name_value3", "price3": "price_value3"}, 
            20: {"name": "name_value2", "price2": "price_value2"}}
    
    keys_ = list(input.keys())
    sorted_keys = sort_keys(keys_)
    out = {key:input[key] for key in sorted_keys}