python - 如何从列表创建字典

标签 python string python-3.x list dictionary

我有一个句子列表,我想将其转换为仅包含用户名和年龄的词典。

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/

相关文章:

javascript - 用javascript替换字符串中的字符

c++ - 使用 c_str() 时 std::string 的未定义行为

python - 在 Python 程序中处理大量对象

python - itertools 无法将 numpy 整数识别为 Python 3.6 上的有效输入

python - 如果行包含列中列表中的两个值,如何过滤数据框

C# : Change String Encoding?

python - 为什么 tkinter 在 Mac 上失败

javascript - 尝试执行 driver.execute_script(gooogletag

python - 保持 url 中的文本干净

python - 如何使用 Python boto3 从 AWS DynamoDB 表中获取特定属性的所有项目?