Home > Net >  Printing dictionary without brackets
Printing dictionary without brackets

Time:09-24

I'm trying to write a script for an exercise that allows me to sort out the characters on a string and count the highest recurring characters but I can't seem to print out the results in a form of a string as its a tuple. Anyone has any idea on how I could do it would be much appreciated.

import sys

stringInput = (sys.argv[1]).lower()
stringInput = sorted(stringInput)
DictCount = {}
Dictionary = {}


def ListDict(tup, DictStr):
    DictStr = dict(tup)
    return DictStr


for chars in stringInput:
    if chars in Dictionary:
        Dictionary[chars]  = 1
    else:
        Dictionary[chars] = 1

ListChar = sorted(Dictionary.items(), reverse=True, key=lambda x: x[1])

Characters = (ListChar[0], ListChar[1], ListChar[2], ListChar[3], ListChar[4])

print(ListDict(Characters, DictCount))

current output:

python3 CountPopularChars.py sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS
{'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}

desired output:

d:7,s:7,e:6,j:4,w:3

CodePudding user response:

create your output in this way:

output = ','.join(f"{k}:{v}" for k, v in ListChar)
print(output)

Output:

e:17,d:7,a:3,b:1,c:1

CodePudding user response:

Try:

yourDict = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
print(','.join("{}:{}".format(k, v) for k, v in yourDict.items()))

Output:

d:7,s:7,e:6,j:4,w:3

CodePudding user response:

Or just:

>>> dct = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
>>> ','.join(f'{k}:{v}' for k,v in dct.items())
'd:7,s:7,e:6,j:4,w:3'

CodePudding user response:

Your code is highly redundant. You could write it in a much more concise way by using collections.Counter to help:

from collections import Counter

# Hard coded stringInput for ease in this test
stringInput = 'sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS'.lower()

c = Counter(stringInput)

ListChar = sorted(c.items(), reverse=True, key=lambda x: x[1])

print(','.join(f"{k}:{v}" for k, v in ListChar[:5]))
  • Related