python - 如何从列表中获取键和值以添加到字典中

标签 python

所以我试图构建一个字典,其中键是列表的第一个元素,其余元素是值,因此它具有以下格式: {str: [str, str, str, int, str]} 但现在我不明白如何从列表中获取第一个元素作为键,其余元素作为值。 这是一个例子:

这是列表

['asmith', 'Alice', 'Smith', '31', 'F', 'alice.smith@example.com']

第一个元素[0]是键,其余元素是值

这是我到目前为止所拥有的:

def create_dict(my_file):
    information = my_file.read()
    information = information.split()
    res = []
    for element in information:
        res.append(element)
    print(res)
    print(res[0])
    d = dict((res[0], res[1:6]) for res[0] in res[1:6])
    print(d)

最佳答案

你的理解困惑了:

d = dict((res[0], res[1:6]) for res[0] in res[1:6])

您可以在循环中执行类似的操作,假设 res 是列表的列表:

d = {}
for r in res:
    d[r[0]] = r[1:6]

或者使用理解:

d = {r[0]:r[1:6] for r in res}

关于python - 如何从列表中获取键和值以添加到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40551707/

相关文章:

python - 如何检查形状文件多边形包含纬度和经度点的 numpy meshgrid

Python/Django 不附加斜杠

Python:增加字典中的 int 值

python - 在带有 BeautifulSoup 的 Python 3 中,print(soup.get_text()) 在以下代码 : 中生成错误 ('NoneType' object is not callable)

不是来自文件系统的 Python 包

python - 比较多个字符串

python - 是否有一种优雅的替代方法可以在不使用大量 if 语句的情况下过滤这些结果?

python - 如何将对象类型的列转换为 HexaDecimal

Python组织小项目/脚本

python - Holoviews 按分类数据散点图颜色