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?
Answers:
for order in orders:
for item in order["line_items"]:
del item["taste"]
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.
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?
for order in orders:
for item in order["line_items"]:
del item["taste"]
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.