-5

I'm trying to do this:

i = 1
for item in cart:
    data_ps['itemId' + i] = item
    i += 1

But Python returns me an error: can only concatenate str (not "int") to str.

Any idea how to increment the value of a key in a dict?

martineau
  • 119,623
  • 25
  • 170
  • 301
Felipe Dourado
  • 441
  • 2
  • 12

3 Answers3

1

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())
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

You can try this

i=1
for item in cart:
    data_ps['itemId' + str(i)] = item
    i += 1
0

This is also another way you can do it, and helps in case you are more familiar with C/C++:

i = 1
for item in cart:
    data_ps["itemId%d" % i] = item
    i += 1

Where %d means to insert an integer value in this position