简体   繁体   English

当键是字符串的第二个值时,如何将多个字符串列表附加到字典中的键?

[英]How can I append multiple lists of strings to a key in dictionary when the key is the second value of a string?

Let's say I have 假设我有

data = [['Sea', 'Blue', 'Fish', 'Swim'], 
    ['Bored', 'Annoyed', 'Frustrated', 'Done'], 
    ['Keyboard', 'Blue', 'Desktop', 'Mouse']]

I need to have the function to return 我需要具有返回的功能

{'Blue': [['Sea', 'Fish', 'Swim'], ['Keyboard', 'Desktop', 'Mouse']],    
    'Annoyed': [['Bored', 'Frustrated, 'Done']]}

I have this function I made 我有这个功能

def func():
    b = dict()
    for element in data:
        for i in element:
                if i[1] in b:
                    b[i[1]].append(i[0], i[2], i[3])
                else:
                    b[i[1]] = (i[0], i[2], i[3])

But it returns: 但它返回:

builtins.IndexError: string index out of range

I hope this made sense, thank you in advance 我希望这是有道理的,预先感谢您

You are nesting too many loops. 您嵌套了太多的循环。 element is already the inner list like ['Sea', 'Blue', 'Fish', 'Swim' , etc. i is therefore the characters of the string. element已经是内部列表,例如['Sea', 'Blue', 'Fish', 'Swim'等。因此, i是字符串的字符。

There are some other problems, see the comments below: 还有其他一些问题,请参见下面的评论:

def func():
    b = dict()
    for element in data:
        if element[1] in b:
            b[element[1]].append([element[0], element[2], element[3]]) # append takes one argument
        else:
            b[element[1]] = [[element[0], element[2], element[3]]]  # list, not tuple
    return b  

暂无
暂无

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

相关问题 如何将值附加到具有多个“值”的字典键? - How can I append a value to a dictionary key with multiple "values"? 如何将多个列表附加到python字典中的一个键? - How do I append multiple lists to one key in a python dictionary? 如果 value 与给定字典中的 key 相等,我怎么能 append 到 key 的 value 的第一个 key - If value is equal with a key in the given dictionary, how can I append to the key of the said value the value of the first key 我怎样才能 append 字典的每个键和值到列? - How can I append each key and value of dictionary to columns? 如何使用函数将新键和值附加到列表字典中 - How to append a new key and value into a dictionary of lists using a function 如何将键值对附加到以索引值作为键对的空字典中? - How can I append key,value pair to empty dictionary with the index value as the key pair? 我如何将字典 append 作为现有字典键的另一个值 - How do I append a dictionary as another value to an existing dictionary key 如何将字符附加到用作python字典键的字符串(当有多个与该字符串相关的条目时)? - How to append characters to a string being used as a python dictionary key (when there are multiple entries related to that string)? 如何在另一个字典中将字典附加为键的值? - How to append a dictionary as a value of a key in another dictionary? 如何使用python将多个键和值附加到嵌套字典中? - How to append multiple key and value into a nested dictionary using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM