Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if any element in a dictionary changes?

Rather than saving a duplicate of the dictionary and comparing the old with the new, alike this:

dict = { "apple":10, "pear":20 }

if ( dict_old != dict ):
   do something
   dict_old = dict

How is it possible to detect WHEN any element of a dictionary changes?

like image 463
crankshaft Avatar asked Oct 04 '14 02:10

crankshaft


People also ask

How do you check if an element is in a dictionary?

You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.

How do you check if values in a dictionary are the same?

Method #1: Using loop In this, we iterate for all the values and compare with value in dictionary, if any one is different, then False is returned.

How do you check if a word is in a dictionary Python?

To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.

Are dictionary items mutable?

Dictionary is a built-in Python Data Structure that is mutable. It is similar in spirit to List, Set, and Tuples. However, it is not indexed by a sequence of numbers but indexed based on keys and can be understood as associative arrays. On an abstract level, it consists of a key with an associated value .


1 Answers

You could subclass dict and include some custom __setitem__ behavior:

class MyDict(dict):
    def __setitem__(self, item, value):
        print "You are changing the value of %s to %s!!"%(item, value)
        super(MyDict, self).__setitem__(item, value)

Example usage:

In [58]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:class MyDict(dict):
:    def __setitem__(self, item, value):
:        print "You are changing the value of %s to %s!!"%(item, value)
:        super(MyDict, self).__setitem__(item, value)
:--

In [59]: d = MyDict({"apple":10, "pear":20})

In [60]: d
Out[60]: {'apple': 10, 'pear': 20}

In [61]: d["pear"] = 15
You are changing the value of pear to 15!!

In [62]: d
Out[62]: {'apple': 10, 'pear': 15}

You would just change the print statement to involve whatever checking you need to perform when modifying.

If you are instead asking about how to check whether a particular variable name is modified, it's a much trickier problem, especially if the modification doesn't happen within the context of an object or a context manager that can specifically monitor it.

In that case, you could try to modify the dict that globals or locals points to (depending on the scope you want this to happen within) and switch it out for, e.g. an instance of something like MyDict above, except the __setitem__ you custom create could just check if the item that is being updated matches the variable name you want to check for. Then it would be like you have a background "watcher" that is keeping an eye out for changes to that variable name.

The is a very bad thing to do, though. For one, it would involve some severe mangling of locals and globals which is not usually very safe to do. But perhaps more importantly, this is much easier to achieve by creating some container class and creating the custom update / detection code there.

like image 73
ely Avatar answered Nov 10 '22 23:11

ely