I have this code that runs without error:
result={}
for i in range(1):
a="Bug: from the English bug — bug, bug, bug in the program".split()
result[a[0][0:-1]]=result.get(a[0][0:-1],[]) + [' '.join(a[1:])] # ' '.join(a[1:]) - error
print(result)
However, I do not want to add a one-element list to the .get result, but a string, like so:
result={}
for i in range(1):
a="Bug: from the English bug — bug, bug, bug in the program".split()
result[a[0][0:-1]]=result.get(a[0][0:-1],[]) + ' '.join(a[1:])
print(result)
But this causes an error that says TypeError: can only concatenate list (not "str") to list. Why?
>Solution :
When you run your get(a[0][0:-1], []), the a[0][0:-1] or Bug key does not exist, so instead it instantiates the ‘Bug’ key in the dictionary and sets its value to the empty list []. At that point, an addition operator is treated as a concatenation and you can only concatenate lists to lists.
You can alternatively use a default value of an empty string '' instead in your get and then you can use ' '.join(a[1:]).
result = {}
for i in range(1):
a = "Bug: from the English bug — bug, bug, bug in the program".split()
result[a[0][0:-1]] = result.get(a[0][0:-1], '') + ' '.join(a[1:])
print(result)