繁体   English   中英

如何从列表中创建字典

[英]how to create a dictionary from a list

我有一个句子列表,我想将它转换成一个词典,只包括用户名和年龄。

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}

尝试词典理解:

dic = {x.split()[0].strip(',@'): int(x.split()[-1]) for x in member_list}

如果您需要澄清表达的各个部分,请告诉我们。

编辑:澄清,根据要求:

好的,所以:

  • 将表达式括在{}告诉它我们正在用这种理解来制作一本字典。 x表示此理解中的每个成员字符串
  • x.split()将字符串拆分为子字符串列表,在“空格”符号上(默认情况下,可以调整)

    • [0]我们抓住第一个子串[“@ David,”]
    • 使用.strip(',@')我们删除名称周围的逗号和@字符
    • 有了这个,我们创建了字典键
  • 键值: int(x.split()[-1])

    • x.split()[-1]取最后一个子串('27')
    • 将它括在int()我们把它变成一个整数

您可以使用字典理解

l = ['@David, the age is 27', '@John, the age is 99', '@rain, the age is 45']


X = {item.split(',')[0][1:]:int(item.split(',')[1].rsplit(maxsplit=1)[-1]) for item in l}
print(X)

#output
{'David': 27, 'John': 99, 'rain': 45}

暂无
暂无

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

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