如何从python中的字符串创建字典

时间:2020-08-16 05:38:07

标签: python string dictionary

CloseRequestFcn

输出应为

StartupFcn

有直接内置的功能吗?

4 个答案:

答案 0 :(得分:7)

>>> import collections
>>> s = 'wednesday'
>>> collections.Counter(s)
Counter({'e': 2, 'd': 2, 'w': 1, 'n': 1, 's': 1, 'a': 1, 'y': 1})

答案 1 :(得分:0)

string = "wednesday"
dic = dict()
for character in string:
  dic[character] = dic.get(character, 0) + 1
print (dic)

答案 2 :(得分:-1)

复制并粘贴

1,560,000

output = my_str='wednesday' d={} for i in my_str: num=1 d [i] = num num=num+1

答案 3 :(得分:-2)

您可以使用字典理解,如此答案中所述:Python Dictionary Comprehension

my_str = 'wednesday'
d = { ch:(my_str.count(ch)) for ch in my_str }
print(d)