从字符串向字典分配键 [英] Assigning keys to a dictionary from a string

查看:65
本文介绍了从字符串向字典分配键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为sentence的字符串:'the sly fox jumped over the brown dog'

I have a string called sentence: 'the sly fox jumped over the brown dog'

我需要创建一个名为Positions的字典. Positions的键应为sentence中的字符. 这些值应该是这些字符的索引.

I need to create a dictionary called Positions. The keys for Positions should be the characters in sentence. The values should be the index for those characters.

例如,所需的输出将是:

For example the desired output would be:

{'t':0, 'h':1, 'e':2, ' ':3 ...}等,等等.

我当然可以手动将其写出,但实际上我被要求将字符串转换为键,而无需手动将其写出.

Of course I can write this out manually, but I think I'm actually being asked to convert the string into keys without writing them out manually.

到目前为止,我刚刚创建了一个空字典,并尝试在事件之后为其分配键和值:

So far I've just created an empty dictionary and am trying to assign keys and values to it after the event:

Positions = {}

我是从错误的脚开始吗?

Have I started off on the wrong foot?

推荐答案

您可以执行以下操作:

result = {}
s = 'the sly fox jumped over the brown dog'

for i, c in  enumerate(s):
    result.setdefault(c, []).append(i)

print(result)

输出

{'m': [14], 'e': [2, 16, 21, 26], 'v': [20], 's': [4], 'n': [32], 'h': [1, 25], 'w': [31], 'l': [5], 'o': [9, 19, 30, 35], 'x': [10], 'p': [15], 'd': [17, 34], 'g': [36], 't': [0, 24], 'u': [13], 'f': [8], 'y': [6], 'b': [28], 'j': [12], ' ': [3, 7, 11, 18, 23, 27, 33], 'r': [22, 29]}

请注意,上述解决方案考虑了重复字符的大小写,并创建了索引列表.

Note that the above solution contemplates the case for repeated characters and it creates a list of the indices.

这篇关于从字符串向字典分配键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆