Reputation: 25
When I tried to run this code I'm getting a TypeError
like this:
items[i[id]] = i
TypeError: string indices must be integers
And here is my code:
x = {
'1': {
'id': 1,
'name': 'Burger',
'price': 10,
'quantity': 2
},
'2':{
'id': 2,
'name': 'Pizza',
'price': 15,
'quantity': 5
},
'3': {
'id': 1,
'name': 'Burger',
'price': 10,
'quantity': 5
},
}
items = {}
counter = 0
for i in x:
if items:
for j in items:
if j['id'] == i['id']:
j['quantity'] = j['quantity'] + i['quantity']
counter = 1
else:
items[i[id]] = i
if counter != 1:
items[i[id]] = i
print(items)
Upvotes: 0
Views: 852
Reputation: 1171
By default, id
is a built-in function in Python. In your code, you never set the variable id
to anything else, so id
is still this built-in function. Also, when you write for i in x
, where x
is a dictionary, i
is a key to this dictionary, and this key is a string. These two things together explain your error.
In the following code:
items[i[id]] = i
the Python interpreter attempts to use id
as an index into the string i
. This doesn't work because id
is a function, not an integer, hence the resulting TypeError
.
As others have noted, you probably meant to write i['id']
, not i[id]
. Furthermore, you probably meant for i
to be one of the values in the dictionary x
, not one of its keys.
Upvotes: 1
Reputation: 127
Its an easy fix, Use .values() to get the values of the key value pairs,
like : for i in range x.values():
Here is the corrected code :
x = {
'1': {
'id': 1,
'name': 'Burger',
'price': 10,
'quantity': 2
},
'2':{
'id': 2,
'name': 'Pizza',
'price': 15,
'quantity': 5
},
'3': {
'id': 1,
'name': 'Burger',
'price': 10,
'quantity': 5
},
}
items = {}
counter = 0
for i in x.values():
if items:
for j in items.values():
if j['id'] == i['id']:
j['quantity'] = j['quantity'] + i['quantity']
counter = 1
else:
items[i['id']] = i
if counter != 1:
items[i['id']] = i
print(items)
Output :
{1: {'id': 1, 'name': 'Burger', 'price': 10, 'quantity': 7}, 2: {'id': 2, 'name': 'Pizza', 'price': 15, 'quantity': 5}}
Upvotes: -1
Reputation: 3860
As far as I understand, you want to obtain a new dict, unified on id
value and a new quantity
is a sum of all quantities with that id
. If we suppose that id
and quantity
are always present at x
values and quantity
is an integer, you can do it this way:
x = {
'1': {
'id': 1,
'name': 'Burger',
'price': 10,
'quantity': 2
},
'2':{
'id': 2,
'name': 'Pizza',
'price': 15,
'quantity': 5
},
'3': {
'id': 1,
'name': 'Burger',
'price': 10,
'quantity': 5
},
}
items = {}
counter = 0
for key, item in x.items():
if item['id'] in items:
items[item['id']]['quantity'] += item['quantity']
else:
items[item['id']] = item
print(items)
Output:
{1: {'id': 1, 'name': 'Burger', 'price': 10, 'quantity': 7}, 2: {'id': 2, 'name': 'Pizza', 'price': 15, 'quantity': 5}}
Upvotes: 2