Reputation: 17
so I have to delete 32.32 from the key 'breakfast blend' in my dictionary How can I remove a single value??
print(transaction_dic_11)
for k in list(transaction_dic_11):
if transaction_dic_11[k] == 32.32:
del transaction_dic_11[k]
Transaction_dic = {'Classic': [37.33, 46.75, 28.18, 33.35],
'breakfast blend':[32.32, 46.94, 26.91, 22.03],
'rev it up': [45.82, 33.89]}`
I tried this code, but it won't delete the value and no changes occur.
Upvotes: 0
Views: 76
Reputation: 27306
In this particular case you can simply do this:
Transaction_dic['breakfast blend'].remove(32.32)
However, floating point numbers are not always what they seem. You may have to look for values that are "close" to the value using some mechanism of tolerance you will need to devise.
Here's an example of how you might approach this:
def remove_if_near(_list, n, tolerance=0.000001):
for i, x in enumerate(_list):
if abs(x - n) < tolerance:
_list.pop(i)
break
return _list
my_list = [1/3, 1/5, 1/9]
print(my_list)
print(remove_if_near(my_list, 0.333333))
Output:
[0.3333333333333333, 0.2, 0.1111111111111111]
[0.2, 0.1111111111111111]
Note:
If the list is sorted then this can be made more efficient. If not sorted then this will potentially be very inefficient for large lists
Upvotes: 0
Reputation: 3755
transaction_dic_11[k] == 32.32
is ALWAYS falseBecause transaction_dic_11[k]
value is a list, not a int.
for k in list(transaction_dic_11):
print(transaction_dic_11[k])
# [37.33, 46.75, 28.18, 33.35]
# [32.32, 46.94, 26.91, 22.03]
# [45.82, 33.89]
# You can see that you have lists, not an int
if transaction_dic_11[k] == 32.32:
del transaction_dic_11[k]
.remove()
You need to detect if the value is IN the list, and remove it if necessary.
LBYL approach:
if 32.32 in transaction_dic_11['breakfast blend']:
transaction_dic_11['breakfast blend'].remove(32.32)
EAFP approach:
try:
transaction_dic_11['breakfast blend'].remove(32.32)
except ValueError:
pass
LBYL vs EAFP: Preventing or Handling Errors in Python
Upvotes: 1