The problem is that 'itemId'
is a string and i
is an integer, and they can’t be added without some form of manipulation, like 'itemId' + str(i)
.
If you have a relatively recent version of Python (3.6 or better), f-strings
provide a nice way to do this(a):
i = 1
for item in cart:
data_ps[f"itemId{i}"] = item
i += 1
However, since it appears that you start from 1
regardless, there’s a good chance you’re creating a dictionary data_ps
from scratch each time rather than adding to it. If that is the case, you can use dictionary comprehension to do this in a one-liner (the second line below):
>>> cart = ["apple", "banana", "carrot"]
>>> data_ps = {f"itemId{i+1}":cart[i] for i in range(len(cart))}
>>> print(data_ps)
{'itemId1': 'apple', 'itemId2': 'banana', 'itemId3': 'carrot'}
(a) They have the advantage over string concatenation and string.format()
in that they read better: the item that goes into the string is right there in the string itself, at the point where it will go. Contrast the line below with those following and you’ll see what I mean:
tmpFile = f"/tmp/{user}_tmp_{os.getpid()}_dir"
tmpFile = "/tmp/" + user + "_tmp_" + os.getpid() + "_dir"
tmpFile = "/tmp/{}_tmp_{}_dir",format(user, os.getpid())
solved Increment the value of a key? [duplicate]