我有一个句子列表,我想将其转换为仅包含用户名和年龄的词典。
list=['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']
我想要得到的输出是像这样的字典
dic={David:27,John:99,rain:45}
感谢您的帮助
最佳答案
您可以定义一个自定义函数,通过map
将其应用到每个字符串,然后输入到dict
:
L = ['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']
def key_value_extractor(x):
x_split = x.split(',') # split by ','
name = x_split[0][1:] # take 1st split and exclude first character
age = int(x_split[1].rsplit(maxsplit=1)[-1]) # take 2nd, right-split, convert to int
return name, age
res = dict(map(key_value_extractor, L))
{'David': 27, 'John': 99, 'rain': 45}
关于python - 如何从列表创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036474/