如何将逗号分隔的字符串转换为字符串,其中键是一个项目,值是键的长度

问题描述 投票:-3回答:2

我正在尝试编写一个函数,给定一个由逗号分隔的项目字符串(stringOfItems),创建一个字典,其中每个键都是一个项目,每个键的关联值是该键中的字符数。

然后该函数应该返回字典。

例如,给定此字符串:

"bubblegum,square,puddle,abcd"

该函数应返回:

{'bubblegum':9,'square':5,'puddle':6,'abcd':4}
python python-3.x string dictionary
2个回答
1
投票

您可以拆分字符串中的元素并使用字典理解构建字典,使用每个术语作为key,将其len作为value

s = "bubblegum,square,puddle,abcd"
{i:len(i) for i in s.split(',')}
# {'bubblegum': 9, 'square': 6, 'puddle': 6, 'abcd': 4}

或者使用for循环:

d = dict.fromkeys(s.split(','))
for k in d:
    d[k] = len(k)

0
投票
stringOfItems = "one,two,three,sixteen"

items = stringOfItems.split(",")
myDict = {}
for i in items:
    myDict[i] = len(i)

print(myDict)
© www.soinside.com 2019 - 2024. All rights reserved.