简体   繁体   English

将字符串映射到以索引为键的字典中

[英]Map characters a strings into dictionary with index as key

i am new in python coding, I am trying to map characters a strings into dictionary with index as key.我是 python 编码的新手,我试图将字符串映射到以索引为键的字典中。 I'm using a string "asleep" and want to get output as我正在使用字符串“asleep”并希望将输出作为

{0: 'a', 1: 's', 2: 'l', 3: 'e', 4: 'e', 5: 'p'}

I'm using the following code:我正在使用以下代码:

myWord = "asleep"

char_count = map(lambda x: dict(enumerate(x)), myWord)

print(char_count)

Output:输出:

{'a': 1, 's': 1, 'l': 1, 'e': 2, 'p': 1}

Simplest solution:最简单的解决方案:

>>> word = 'asleep'
>>> dict(enumerate(word))
{0: 'a', 1: 's', 2: 'l', 3: 'e', 4: 'e', 5: 'p'}

This works because enumerate returns an iterable of pairs like (0, 'a') , (1, 's') , and so on;这是有效的,因为enumerate返回像(0, 'a')(1, 's')等对的可迭代对象; and the dict constructor works with an iterable of (key, value) pairs.并且dict构造函数使用可迭代的 (key, value) 对。

您可以尝试以下行:

dict(zip(range(len(myWord)), myWord))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM