简体   繁体   English

如何将字典值从字符串转换为列表?

[英]How to convert dictionary values from string to list?

I have a dictionary in which the values are strings and I need them to be lists. 我有一本字典,其中的值是字符串,我需要它们作为列表。 So I tried to do: 所以我尝试做:

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

However, it return an error that is, string index out of range 但是,它返回一个错误,即字符串索引超出范围

My whole code is: 我的整个代码是:

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

If you wish to get dict with string values replaced with lists: 如果您希望使用用列表替换的字符串值来获取字典:

>>> 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']}

How about: 怎么样:

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

or based on the clarification in the comment: 或基于评论中的说明:

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

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

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