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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.