Home > front end >  TypeError: string indices must be integers (dictionaries)
TypeError: string indices must be integers (dictionaries)

Time:01-15

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)

CodePudding user response:

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

CodePudding user response:

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}}
  •  Tags:  
  • Related