简体   繁体   中英

Can you access a python dictionary key's value from a function in that dictionary?

I know how to add a function to a python dict:

def burn(theName):
        return theName + ' is burning'

kitchen = {'name': 'The Kitchen', 'burn_it': burn}
    
print(kitchen['burn_it'](kitchen['name']))

### output: "the Kitchen is burning"

but is there any way to reference the dictionary's own 'name' value without having to name the dict itself specifically? To refer to the dictionary as itself?

With other languages in mind I was thinking there might be something like

print(kitchen['burn_it'](__self__['name']))

or

print(kitchen['burn_it'](__this__['name']))

where the function could access the 'name' key of the dictionary it was inside.

I have googled quite a bit but I keep finding people who want to do this:

kitchen = {'name': 'Kitchen', 'fullname': 'The ' + ['name']}

where they're trying to access the dictionary key before they've finished initialising it.

TIA

You cannot know which object reference the function.

A simple example, image the following:

def burn(theName):
        return theName + ' is burning'

kitchen = {'name': 'The Kitchen', 'burn_it': burn}
garage = {'name': 'The Garage', 'burn_it': burn}

burn is referenced both in kitchen and garage , how could it "know" which dictionary is referencing it?

id(kitchen['burn_it']) == id(garage['burn_it'])
# True

What you can do (if you don't want a custom object) is to use a function:

def action(d):
    return d['burn_it'](d['name'])

action(kitchen)
# 'The Kitchen is burning'

action(garage)
# 'The Garage is burning'

with a custom object:

class CustomDict(dict):
    def __init__(self, *arg, **kwargs):
        super().__init__(*arg, **kwargs)
        
    def action(self):
        return self['burn_it'](self['name'])
    
kitchen = CustomDict({'name': 'The Kitchen', 'burn_it': burn})

kitchen.action()
# 'The Kitchen is burning'

You can extend dict object with your custom class, like this:

class MyDict(dict):
    def __init__(self, *args, **kwargs):
        self["burn_it"] = self.burn
        super().__init__(*args, **kwargs)
        
    def burn(self):
        return self["name"] + " is burning"

kitchen = MyDict({'name': 'The Kitchen'})
    
print(kitchen['burn_it']()) # The Kitchen is burning
print(kitchen.burn())       # The Kitchen is burning

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM