• + 0 comments

    First time using lambda expression to sort a dictionnary.

    Find my code below.

    The logic is to use collections.Counter to count every letter of the company name. Then sort them firstly by the occurence, then alphabetically.

    At the beginning, I've started by using the most_common() function of Counter, but it was quite difficult to implement it in a lambda expression for me. But As I said, it was my first time with lambda expression. So if you have some advices, I am open.

    Here my code :

    from collections import Counter
    
    if __name__ == '__main__':
        s = input()
        logo_name = Counter(s)
        #print(logo_name.keys())
    
        
        # Sort in the case where few letters have the same number of occurences
        key = lambda item: (-item[1], item[0])
        most_common_letters = sorted(logo_name.items(), key=key)
        #print(most_common_letters)
        
        # 3 most common letters
        most_common_letters = most_common_letters[:3]
        #print(most_common_letters)
        
        for element in most_common_letters:
            item, value = element
            print(f"{item} {value}")