sort and swap in python same time

This tallies repeated characters in a dictionary and then creates a list of the sorted (sorted using max() and dict.pop(key, None)) values

first_str = input('Enter first string >').strip()
second_str = input('Enter second string >').strip()

first_str = first_str.lower()
first_str = set(first_str)
second_str = second_str.lower()

counts = {}

for character in first_str:
    counts [character] = second_str.count(character)

counts_list = []
popdict = {k: v for k,v in counts.items()}
for k in counts:
    key, value = max(popdict, key=popdict.get),max(popdict.values())
    counts_list.append([key,value])
    popdict.pop(key, None)

for sublist in counts_list:
    print (sublist[0]+' = '+str(sublist[1]))

prints:

[['c', 7], ['a', 5], ['b', 3]]
c = 7
a = 5
b = 3

Browse More Popular Posts

Leave a Comment