Access values from a custom function inside a dictionary

python dictionary of functions with parameters
python function as dictionary value
how to store function in dictionary python
python call function with dictionary arguments
dictionary in python 3
python dictionary value
how to get dictionary values in python
python define function in dictionary

I have the following lines of code for a particular use case. (Using python 2.7)

class AutoMap(dict):
    """Implementation of autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
    def __dir__(self):
        return dict.keys()
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

obj = AutoMap()
AddressMap = AutoMap()

obj["state"] = "Maharastra"
obj["country"] = "India"

AddressMap['address1'] = obj

obj["state"] = "California"
obj["country"] = "USA"

AddressMap['address2'] = obj

print AddressMap # {'address1': {'state' : 'Maharastra', 'country' : 'India'}, 'address2': {'state' : 'California', 'country' : 'USA'}}

def prn_state():
    print "State: " + state


AddressMap['address1']['_prn_state'] = prn_state

AddressMap['address2']['_prn_state'] = prn_state


print AddressMap # {'address1': {'state' : 'Maharastra', 'country' : 'India', '_prn_state': <function prn_state at 0x7fb297dc7320>}, 'address2': {'state' : 'California', 'country' : 'USA', '_prn_state': <function prn_state at 0x7fb297dc7320>}}

print type(AddressMap) # <class 'AutoMap'>

print AddressMap.address2._prn_state()

Now, I want whenever I write this line of code it should print "California". But, it throws an error saying "NameError: global name 'state' is not defined"

AddressMap is a dict, to get the state value of the address2:

AddressMap = {'address1': {'state' : 'Maharastra', 'country' : 'India'}, 
              'address2': {'state' : 'California', 'country' : 'USA'}}    
print(AddressMap['address2']['state'])

EDIT:

Wrapped in a function:

def states(AddressMap, address):
    return AddressMap[address].get('state', 'Not found')

AddressMap = {'address1': {'state' : 'Maharastra', 'country' : 'India'}, 'address2': {'state' : 'California', 'country' : 'USA'}}
print(states(AddressMap, 'address2'))

OUTPUT:

California

Why store a function inside a python dictionary?, The key doesn't need to be hardcoded though, as in your example. Usually, this is a form of caller dispatch, where you use the value of a variable to connect to a � Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value, so that they can be retrieved efficiently.. Let’s discuss various ways of accessing all the keys along with their values in Python Dictionary.

As the error tells you, state is not defined in the global context. This is working:

class AutoMap(dict):
    """Implementation of autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
    def __dir__(self):
        return dict.keys()
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def prn_state(self):
        print "State: " + self.state

obj = AutoMap()
AddressMap = AutoMap()

obj["state"] = "Maharastra"
obj["country"] = "India"

AddressMap['address1'] = obj

obj["state"] = "California"
obj["country"] = "USA"

AddressMap['address2'] = obj

print AddressMap

AddressMap['address1']['_prn_state'] = AddressMap['address1'].prn_state

AddressMap['address2']['_prn_state'] = AddressMap['address2'].prn_state


print AddressMap

print type(AddressMap)

AddressMap.address2._prn_state()

Python Dictionary (With Examples), While indexing is used with other data types to access values, a dictionary uses keys . Keys can be used either inside square brackets [] or with the get() method. The problem with this, however, is that this object doesn’t behave as a dictionary – if you want to use any of the dictionary methods, you need to access __dict__ directly (or use the dictionary that this object was created from). Another approach is to subclass dict and add attribute getter and setter methods:

class AutoMap(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
    def __dir__(self):
        return dict.keys()

    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


class Sample:
    def __init__(self, d): 
        self.test = d
    def prn_state(self): 
        print self.test.state

obj = AutoMap()
AddressMap = AutoMap()

obj["state"] = "Maharastra"
obj["country"] = "India"
obj["sample"] = Sample(obj)
AddressMap['address1'] = obj

obj["state"] = "California"
obj["country"] = "USA"
obj["sample"] = Sample(obj)
AddressMap['address2'] = obj

AddressMap.address2.sample.prn_state()

Tutorial: Why Functions Modify Lists, Dictionaries in Python, Python's functions (both the built-in ones and custom functions we write To understand how Python handles global variables inside functions, let's over each value in the dictionary, adding them to the count so we get the� Implements IDictionary<TKey, TValue> interface. Keys must be unique and cannot be null. Values can be null or duplicate. Values can be accessed by passing associated key in the indexer e.g. myDictionary [key] Elements are stored as KeyValuePair<TKey, TValue> objects.

Dictionary Data Structures in Python 3, By making use of dictionaries' key-value pairs, we can reference keys to retrieve values. In addition to using keys to access values, we can also work with some built-in methods: To return the keys, we would use the dict.keys() method. Creating custom access formulas and functions in VBA offer several advantages over using expressions. For one, you can easily debug VBA code to aid validating the logic or the result. Next, you don’t have to worry about balancing parentheses and square brackets as VBA allows you to write the same expression above but simply, like this:

Python - Dictionary, Keys are unique within a dictionary while values may not be. If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows − Note − del() method is discussed in subsequent section. They can be any arbitrary Python object, either standard objects or user-defined objects. As we can see, here the global value of initial_list was updated, even though its value was only changed inside the function! Dictionaries. Now, let’s write a function that takes a dictionary as an argument to see if a global dictionary variable will be modified when it’s manipulated inside a function as well.

Python Dictionary with Methods, Functions and Dictionary , Python Dictionary: How to Create Dictionary in Python, access, Separate keys from values with a colon(:), and a pair from another by a comma(,). So if you pass it three lists, you must pass them inside a list or a tuple. ' This function returns a dictionary object which can hold multiple values. Public Function GetDict () As Dictionary Dim var As Dictionary Set var = New Dictionary ' The "key" is the item name and the "value" is the description. var.Add "First Name", "John" var.Add "Last Name", "Star" Set GetDict = var End Function

Comments
  • prn_state is a function that returns nothing, how are you assigning AddressMap[address1]['_prn_state'] = prn_state
  • Just provide your code instead of mixing output with it
  • Also, state inside the function is undefined
  • Thanks :) But actually it's not a dict, it's a class. I have edited my question and given the entire code.
  • Thanks it helped. :) But the output is shown as "State: California None". Can you tell why None? Any solution?
  • @SarfarazHussain Are you sure that you also changed the last line from print AddressMap.address2._prn_state() to AddressMap.address2._prn_state() ?
  • Yeah now it worked without "print". Thanks. But can we achieve the same without making prn_state() a member function of AutoMap class?