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
#1
Hello,

The input is this:

Output:
{'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']}
And the output is supposed to be this:
Output:
{'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}
Note that values of each key are sorted.

My code is this:

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[1])}

    return output_dict
But this code is not producing the expected result. What am I missing here?
Larz60+ write Oct-27-2020, 04:37 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Fixed for you this time, please use bbcode tags on all future posts.
Reply


Messages In This Thread
Swap key and value of a dictionary - and sort it - by Omid - Oct-27-2020, 03:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 2 709 Apr-29-2024, 04:38 PM
Last Post: Calab
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,389 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  How to swap two numbers in fields in python Joni_Engr 5 2,009 Jan-11-2022, 09:43 AM
Last Post: menator01
  swap elements in list hshivaraj 3 12,645 Apr-22-2019, 09:23 AM
Last Post: Yoriz
  Sort MULTIDIMENSIONAL Dictionary mirinda 2 4,983 Apr-05-2019, 12:08 PM
Last Post: perfringo
  I am trying to swap two variables with a Function.... Jeff_Waldrop 4 3,189 Mar-04-2019, 10:19 AM
Last Post: Jeff_Waldrop
  yes-no RE pattern swap bluefrog 1 2,706 Jun-08-2018, 07:06 AM
Last Post: volcano63
  Randomise network while maintaining topology of nodes using edge-swap approach Tom1988 3 4,209 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