【问题标题】:How to convert dictionary values from string to list?如何将字典值从字符串转换为列表?
【发布时间】:2017-05-26 04:49:28
【问题描述】:

我有一个字典,其中的值是字符串,我需要它们是列表。所以我尝试这样做:

for v in dic:
    v[1] = list(v[1])

但是,它返回一个错误,即 字符串索引超出范围

我的整个代码是:

def agrupa_por_chave(lista):
    dic = {
        }
    for t in lista:
        if t[0] not in dic:
            dic[t[0]] = t[1]
        else:
            dic[t[0]] += t[1]
    for v in dic:
        v[1] = list(v[1])
    return dic

【问题讨论】:

  • lista 长什么样子?
  • agrupa_por_chave([('a', 'b'), ('a', 'c')])
  • 添加预期的输入和输出

标签: python python-3.x dictionary python-3.5


【解决方案1】:

如果你想用列表替换字符串值的字典:

>>> l = {1: 'abc', 2: 'def'}

>>> l
{1: 'abc', 
 2: 'def'}

>>> {k:list(v) for k,v in l.items()}
{1: ['a', 'b', 'c'], 
 2: ['d', 'e', 'f']}

【讨论】:

    【解决方案2】:

    怎么样:

    dic = {k: [v] for k, v in dic.items()}
    

    或根据评论中的说明:

    dic = {k: list(v) for k, v in dic.items()}
    

    【讨论】:

    • 不完全。返回列表中的整个值,我需要一个包含值的每个元素的列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2011-07-12
    • 2014-05-23
    • 2019-05-29
    相关资源
    最近更新 更多