首页 > 解决方案 > 打印不带括号的字典

问题描述

我正在尝试为一个练习编写一个脚本,该脚本允许我对字符串上的字符进行排序并计算最高重复出现的字符,但我似乎无法以字符串的形式将结果打印为元组。任何人对我如何做到这一点有任何想法将不胜感激。

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))

电流输出:

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

所需的输出:

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

标签: pythonpython-3.xpython-2.7dictionary

解决方案


以这种方式创建您的输出:

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

输出:

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


推荐阅读