shorter way to delete key from a dictionary

Question:

I have wanted to delete the taste key from the line_items dict list of the entire dictionary list. the code is given below

  orders = [
    {
    'order_id' : 1,
    'line_items': [
                    {
                    'product_id': 2,
                    'product_name' : 'mango',
                    'taste' : 'sweet',

                    },

                    {
                    'product_id':3,
                    'product_name': 'grape',
                    'taste': 'sweet & sour',

                    }
                ],
    },
    {
    'order_id' : 2,
    'line_items': [
                    {
                    'product_id': 4,
                    'product_name' : 'lime',
                    'taste' : 'sour',

                    }
                  ]
    },                  
]

I have already done it. and this is my solution.

delitems = ['taste']
for order in orders:
    for item in order["line_items"]:
        for delkeys in delitems:
            item.pop(delkeys)

But I think it is a bad code and wanted to know if is there any way to shorting my code
with dict comprehension or another way?

Asked By: Bashar

||

Answers:

for order in orders:
    for item in order["line_items"]:
        del item["taste"]
Answered By: Kelly Bundy

Slightly more natural than using dict.pop when you don’t care about the value you’re deleting would be to use the del statement:

del item[delkeys]

Obviously, this doesn’t reduce the number of lines. If you’re only ever deleting the one key, you don’t need the delitems and the loop over it. If you don’t mind hard-coding that "taste" is the key to delete, just do:

for order in orders:
    for item in order["line_items"]:
        del item["taste"]

While you could write a bunch of nested list comprehension and dictionary comprehensions to achieve the same effect in a single statement, it would be a lot harder to understand than your simple nested loop code.

Answered By: Blckknght
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.