0
Follow
2
View

TypeError: string indices must be integers (dictionaries)

beloved840426 注册会员
2023-01-25 00:54

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}}
dangrongjing 注册会员
2023-01-25 00:54

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.

gala42 注册会员
2023-01-25 00:54

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}}