Get keys from a dicionary
John Gordon
gordon at panix.com
Fri Nov 11 12:28:52 EST 2011
In <aac0b123-673b-4d8f-bc05-1f639515a951 at c18g2000yqj.googlegroups.com> macm <moura.mario at gmail.com> writes:
> >>> myDict = {}
> >>> myDict['foo'] = {}
> >>> myDict['foo']['bar'] = 'works'
> -----
> >>> def myFunction( MyObj ):
> ... # MyObj is a nested dicionary (normaly 2 steps like myDict['foo']
> ['bar'])
> ... # I want inspect this MyObj
> ... # what keys was pass
> ... print MyObj.keys() ## WRONG
> ... # So What I want is :
> ... # return foo bar
> ----------------
> >>> result = myFunction( myDict['foo']['bar'] )
> >>> result
> Should print :
> ... foo bar
I don't think there's a simple way to do what you want.
You could inspect the whole dictionary to find the keys that map to a
given value, like so:
def MyFunction(mydict, x):
for k1 in mydict:
for k2 in mydict[k1]:
if mydict[k1][k2] == x:
return "%s %s" % (k1, k2)
>>> print MyFunction(myDict, 'works')
>>> foo bar
--
John Gordon A is for Amy, who fell down the stairs
gordon at panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
More information about the Python-list
mailing list