Home > other >  Why values of my specific key and value in a dictionary don't change in Python?
Why values of my specific key and value in a dictionary don't change in Python?

Time:11-29

I am trying to handle a dictionary that has a list as a value for a key named 'notes' , so I am trying to find the maximum element from that list and reassign the value with that maximum element from the list and also change the key value to 'top_notes' as follows.

Input = top_note({ "name": "John", "notes": [3, 5, 4] })
Output = { "name": "John", "top_note": 5 }.

The output that I am getting is 'None' Below is my code.

class Solution(object):

    def top_notes(self, di):

        for key, values in di.items():
            if key in di == 'notes':
                lt = list(values)
                maximum = max(lt)
                di['top_notes'] = di['notes']
                del di['notes']
                di[maximum] = di[values]
                del di[values]
                return di


if __name__ == '__main__':
    p = Solution()
    dt = {"name": "John", "notes": [3, 5, 4]}
    print(p.top_notes(dt))

CodePudding user response:

When you say

if key in di == 'notes':

what happens is that Python first evaluates key in di which will be True since we are looping over the keys in the di.

It then compares True == 'notes' which will always be False and it will never enter the if clause.

To fix this, just drop the in di part:

if key == 'notes':

CodePudding user response:

Iterating over dict using .items()will yield you a pair of (key, value) Making a list of a single value...gives list with a single value, max of it returns that single item. Your whole function body could be:

di["top_note"] = max(di["notes"])
di.pop("notes", None)
  • Related