Python Forum
Swap key and value of a dictionary - and sort it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Swap key and value of a dictionary - and sort it
#4
It was just the wrong index. Use index 0 if you want to sort by keys and if you use 1, you're sorting by values.

If you sort by keys, you should get this order:
In [45]: sorted("precise clever talented bright smart exact".split())
Out[45]: ['bright', 'clever', 'exact', 'precise', 'smart', 'talented']
For example, you can sort your str also by length:
In [46]: sorted("precise clever talented bright smart exact".split(), key=len)
Out[46]: ['smart', 'exact', 'clever', 'bright', 'precise', 'talented']
Now back to your code:
def reverse_dictionary(input_dict):
    my_dict= {}
    for key, value in input_dict.items():
        for string in value:
            my_dict.setdefault(string.lower(), []).append(key.lower())
    output_dict={k:v for k,v in sorted(my_dict.items(), key=lambda item:item[0])} # not index 1, index 0 is the key
    return output_dict


# first iteration
from operator import itemgetter


def reverse_dictionary(input_dict):
    result = {}
    by_key = itemgetter(0)
    for key, values in input_dict.items():
        for string in values:
            result.setdefault(string.lower(), []).append(key.lower())
    return dict(sorted(result.items(), key=by_key))


# second iteration
from collections import defaultdict
from operator import itemgetter


def reverse_dictionary(input_dict):
    result = defaultdict(list)
    by_key = itemgetter(0)
    for key, values in input_dict.items():
        for string in values:
            result[string.lower()].append(key.lower())
    return dict(sorted(result.items(), key=by_key))


# third iteration
from collections import defaultdict
from operator import itemgetter


def sort_dict_keys(mapping):
    return dict(sorted(result.items(), key=itemgetter(0)))


def reverse_dictionary(input_dict):
    result = defaultdict(list)
    for key, values in input_dict.items():
        for string in values:
            result[string.lower()].append(key.lower())
    return sort_dict_keys(result)
If you have a predefined order, you could use a mapping to int.
Predefined order:
def custom_order(key_value, default=0):
    key, _ = key_value
    key_order = {
        "bright": 1,
        "clever": 2,
        "exact": 100,
        "precise": 3,
        "smart": 4,
        "talented": 5,
    }
    return key_order.get(key, default)
It's not the best example because the dict was defined inside the function.
But I hope it helps to clarify that you can do also custom sort order.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Swap key and value of a dictionary - and sort it - by DeaD_EyE - Oct-28-2020, 09:27 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 2 686 Apr-29-2024, 04:38 PM
Last Post: Calab
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,369 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  How to swap two numbers in fields in python Joni_Engr 5 1,962 Jan-11-2022, 09:43 AM
Last Post: menator01
  swap elements in list hshivaraj 3 12,612 Apr-22-2019, 09:23 AM
Last Post: Yoriz
  Sort MULTIDIMENSIONAL Dictionary mirinda 2 4,957 Apr-05-2019, 12:08 PM
Last Post: perfringo
  I am trying to swap two variables with a Function.... Jeff_Waldrop 4 3,151 Mar-04-2019, 10:19 AM
Last Post: Jeff_Waldrop
  yes-no RE pattern swap bluefrog 1 2,687 Jun-08-2018, 07:06 AM
Last Post: volcano63
  Randomise network while maintaining topology of nodes using edge-swap approach Tom1988 3 4,181 May-25-2017, 10:59 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020