Home > Net >  using for-loop to remove maximum and minimum values from a dictionary
using for-loop to remove maximum and minimum values from a dictionary

Time:10-16

how can I use for loop to delete maximum and minimum values from a dictionary. for instance if you have a dictionary grades = {sam: [23,43,55]}, peter: [66,55,44], sarah: [99,55,77]}. how can I remove only the maximum and minimum values? im new to coding and cannot figure it out. Language is python

CodePudding user response:

Hi you can try something like this:

  # Create dictionary
  dic = {'sam': [23,43,55], 'peter': [66,55,44], 'sarah': [99,55,77]}

  # Use for loop to iterate
  for key, value in dic.items():
      # Find maximum value and it's index
      max_value = max(value)
      max_index = value.index(max_value)

      # Delete maximum value
      del dic[key][max_index]
      
      # Find minimum value and it's index
      min_value = min(value)
      min_index = value.index(min_value)

      # Delete miniumum value
      del dic[key][min_index]

  # Print output
  print(dic)

Let me know if you don't understand anything. Cheers

  • Related