Get keys from a dicionary

M

macm

Hi Folks

I pass a nested dictionary to a function.

def Dicty( dict[k1][k2] ):
print k1
print k2

There is a fast way (trick) to get k1 and k2 as string.

Whithout loop all dict. Just it!

Regards

macm
 
J

Jon Clements

Hi Folks

I pass a nested dictionary to a function.

def Dicty( dict[k1][k2] ):
        print k1
        print k2

There is a fast way (trick) to get k1 and k2 as string.

Whithout loop all dict. Just it!

Regards

macm

I've tried to understand this, but can't tell if it's a question or
statement, and even then can't tell what the question or statement
is...

Care to eloborate?
 
J

John Gordon

In said:
I pass a nested dictionary to a function.
def Dicty( dict[k1][k2] ):

That's not valid syntax.
print k1
print k2
There is a fast way (trick) to get k1 and k2 as string.

Are you stating this can be done, or are you asking if it can be done?
Questions usually end with a question mark. (Are you a native English
speaker?)
Whithout loop all dict. Just it!

print "%s" % x
 
M

macm

Hi

Sorry ! My mistake.
myDict = {}
myDict['foo'] = {}
myDict['foo']['bar'] = 'works'
[/QUOTE]
.... # 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

Best Regards

macm



I pass a nested dictionary to a function.
def Dicty( dict[k1][k2] ):
        print k1
        print k2
There is a fast way (trick) to get k1 and k2 as string.
Whithout loop all dict. Just it!

macm

I've tried to understand this, but can't tell if it's a question or
statement, and even then can't tell what the question or statement
is...

Care to eloborate?
 
M

macm

In said:
I pass a nested dictionary to a function.
def Dicty( dict[k1][k2] ):

That's not valid syntax.
   print k1
   print k2
There is a fast way (trick) to get k1 and k2 as string.

Are you stating this can be done, or are you asking if it can be done?
Questions usually end with a question mark.  (Are you a native English
speaker?)
Whithout loop all dict. Just it!

print "%s" % x

Hi John

I am not a native English speaker. Sorry bad english.

Regards

macm
 
M

macm

Ok Sorry!!

Sorry the noise!!


def func(object):
print "%s" % object


Regards



Hi

Sorry ! My mistake.
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

Best Regards

macm

Hi Folks
I pass a nested dictionary to a function.
def Dicty( dict[k1][k2] ):
        print k1
        print k2
There is a fast way (trick) to get k1 and k2 as string.
Whithout loop all dict. Just it!
Regards
macm
I've tried to understand this, but can't tell if it's a question or
statement, and even then can't tell what the question or statement
is...
Care to eloborate?
 
D

Dave Angel

Hi

Sorry ! My mistake.
myDict = {}
myDict['foo'] = {}
myDict['foo']['bar'] = 'works'
-----
def myFunction( MyObj ):
... # MyObj is a nested dicionary (normaly 2 steps like myDict['foo']
['bar'])

No, it's not. It's a string "works". There's no dictionary passed to
myFunction(), so it cannot do what you ask, slow or fast.

There are games you can play with introspection, but they are neither
portable nor reliable.
... # 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

Best Regards

macm
Can you tell us the exact assignment, to see whether this is supposed to
be a practical question, or a way to try to learn more about Python
internals.
 
J

John Gordon

In said:
myDict = {}
myDict['foo'] = {}
myDict['foo']['bar'] = 'works'
... # 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)
 
G

Gelonida N

Hi Folks

I pass a nested dictionary to a function.

def Dicty( dict[k1][k2] ):
print k1
print k2

There is a fast way (trick) to get k1 and k2 as string.

Whithout loop all dict. Just it!

Regards

macm


I think the answer to the question, that I don't really understand is:
No. This cannot be done.


However we might help you if you copy a COMPLETE standalone example of
your problem and if you try to re-explain once more what exactly you
want to do.

Ideally tell us even why you want to do it. Perhaps the solution is
something completely different.


Below I'm doing some guess work:


nesteddict = { 'a': { 'A' : 'value1 a_A' , 'B' : 'value2 a_B' },
'b': { 'A' : 'value3 b_A' , 'B' : 'value4 b_B' },
'c': { 'A' : 'value3 b_A' , 'B' : 'value4 b_B' },
}

def mymagic_function(value):
print 'the value is <%s>', value
print('There is really no way knowing from where this value came\n'
'except if you tell me in which dictionary you are supposed\n'
'and if I just try to find all matches\n' )

value = nesteddict['a']['B']

mymagic_function(value)
 
G

Gelonida N

Hi Folks

I pass a nested dictionary to a function.

def Dicty( dict[k1][k2] ):
print k1
print k2

There is a fast way (trick) to get k1 and k2 as string.

Whithout loop all dict. Just it!

Regards

macm


If my guessing was correct is this what you are looking for?


nesteddict = { 'a': { 'A' : 'value1 a_A' , 'B' : 'value2 a_B' },
'b': { 'A' : 'value3 b_A' , 'B' : 'value4 b_B' },
'c': { 'A' : 'value3 b_A' , 'B' : 'value4 b_B' },
}

def find_in_nested_dict(adict, avalue):
results = []
for key1, sub_dict in adict.items():
for key2, value in sub_dict.items():
if avalue == value:
results.append( (key1, key2) )
return results

def mk_lookup(adict):
lookup = {}
for key1, sub_dict in adict.items():
for key2, value in sub_dict.items():
entry = lookup.get(value, [])
entry.append( (key1, key2) )
lookup[value] = entry
return lookup

# good if you just want so search one value
value = nesteddict['c']['B']
keys = find_in_nested_dict(nesteddict, value)
print "found %r in %r" % (value, keys)

# if you need many lookups perhaps better to 'precalculate a
# 'reversed' dict
lookup = mk_lookup(nesteddict)
keys = lookup[value]
print "found %r in %r" % (value, keys)
 
J

John Gordon

In said:
If my guessing was correct is this what you are looking for?

He said he didn't want to loop over the dict contents. Without
that, I don't think there's an answer for him.
 
A

alex23

I pass a nested dictionary to a function.

def Dicty( dict[k1][k2] ):
print k1
print k2

There is a fast way (trick) to get k1 and k2 as string.

It might be possible to do something using a reverse dictionary and
getting rid of the nested dictionary.

This is a quick and simple 'two-way' dictionary class that works by
maintaining two dictionaries: the original key/value, and the reversed
value/key. It returns a list of keys, allowing for a value to be
assigned against more than

from collections import defaultdict

class TwoWayDict(dict):
def __init__(self, *args, **kwargs):
self._reversed = defaultdict(list)
for key, val in kwargs.iteritems():
self[key] = val

def __setitem__(self, key, value):
super(TwoWayDict, self).__setitem__(key, value)
self._reversed[value].append(key)

def getkeys(self, match):
return self._reversed[match]
original = TwoWayDict(a=100,b='foo',c=int,d='foo')
original.getkeys(100) ['a']
original.getkeys('foo')
['b', 'd']

As for the nested dictionary, you could replace it with a _single_
dictionary that uses a composite key:
original = TwoWayDict(a=100,b=100)
original.getkeys(100) ['a', 'b']
original = TwoWayDict()
original['record1','user1'] = 'martin'
original['record1','user2'] = 'robert'
original['record2','user1'] = 'robert'
original.getkeys('robert')
[('record1', 'user2'), ('record2', 'user1')]
Whithout loop all dict. Just it!

The TwoWayDict class removes the need to loop across the dict looking
for keys that match a value by replacing it with another dict lookup.
Reducing the nested dict to a single dict with composite keys removes
the need to traverse the outer dict to compare against its children.
 
A

alex23

I pass a nested dictionary to a function.

def Dicty( dict[k1][k2] ):
print k1
print k2

There is a fast way (trick) to get k1 and k2 as string.

It might be possible to do something using a reverse dictionary and
getting rid of the nested dictionary.

This is a quick and simple 'two-way' dictionary class that works by
maintaining two dictionaries: the original key/value, and the reversed
value/key. It returns a list of keys, allowing for a value to be
assigned against more than

from collections import defaultdict

class TwoWayDict(dict):
def __init__(self, *args, **kwargs):
self._reversed = defaultdict(list)
for key, val in kwargs.iteritems():
self[key] = val

def __setitem__(self, key, value):
super(TwoWayDict, self).__setitem__(key, value)
self._reversed[value].append(key)

def getkeys(self, match):
return self._reversed[match]
original = TwoWayDict(a=100,b='foo',c=int,d='foo')
original.getkeys(100) ['a']
original.getkeys('foo')
['b', 'd']

As for the nested dictionary, you could replace it with a _single_
dictionary that uses a composite key:
original = TwoWayDict(a=100,b=100)
original.getkeys(100) ['a', 'b']
original = TwoWayDict()
original['record1','user1'] = 'martin'
original['record1','user2'] = 'robert'
original['record2','user1'] = 'robert'
original.getkeys('robert')
[('record1', 'user2'), ('record2', 'user1')]
Whithout loop all dict. Just it!

The TwoWayDict class removes the need to loop across the dict looking
for keys that match a value by replacing it with another dict lookup.
Reducing the nested dict to a single dict with composite keys removes
the need to traverse the outer dict to compare against its children.
 
M

Matej Cepl

Dne 11.11.2011 14:31, macm napsal(a):
def Dicty( dict[k1][k2] ):

When looking at this I returned to the question which currently rolls in
my mind:

What's difference/advantage-disadvantage betweeng doing multi-level
dicts/arrays like this and using tuple as a key? I.e., is it more
Pythonic to have

dict[k1,k2]

instead?

Best, Matěj
 
T

Tim Golden

Dne 11.11.2011 14:31, macm napsal(a):
def Dicty( dict[k1][k2] ):

When looking at this I returned to the question which currently rolls in
my mind:

What's difference/advantage-disadvantage betweeng doing multi-level
dicts/arrays like this and using tuple as a key? I.e., is it more
Pythonic to have

dict[k1,k2]

instead?

For me, it would depend on what the data meant. To give an obvious
example: if you were storing things which were based on coords, then
clearly map[x, y] is more meaningful than map[x][y]. Conversely, if your
dictionary structure was, say, a set of preferences for users, then
prefs[username][prefname] is probably a more useful model.

Sometimes it's not so clear, in which case one person might opt for one
approach while another opted for another while modelling the same data
concepts. If, for example, you were modelling a set of book reviews
where each review might have one or more genres (which you could display
as a tag-cloud, say) then you could consider the model to be
a sort of book-genre tag cloud:

book_genres[title, genre]

or a list of books in each genre:

genres[genre][title]

or a list of genres for each book:

books[title][genre]

or even multiple ways if that made it easier to use in one situation
or another.

Stating-the-obvious-ly yours,

TJG
 
P

Peter Otten

Matej said:
Dne 11.11.2011 14:31, macm napsal(a):
def Dicty( dict[k1][k2] ):

When looking at this I returned to the question which currently rolls in
my mind:

What's difference/advantage-disadvantage betweeng doing multi-level
dicts/arrays like this and using tuple as a key? I.e., is it more
Pythonic to have

dict[k1,k2]

instead?

If you need lookup only I'd prefer tuples, but sometimes you may want to
retrieve all values with a certain k1 and

d[k1]

is certainly more efficient than

[(k2, v) for (k1, k2), v in d.items() if k1 == wanted]
 
A

alex23

Peter Otten said:
If you need lookup only I'd prefer tuples, but sometimes you may want to
retrieve all values with a certain k1 and

d[k1]

is certainly more efficient than

[(k2, v) for (k1, k2), v in d.items() if k1 == wanted]

This was the hidden cost of the tuple/reverse-dictionary solution I
offered. The solution will of course depend on what the OP requires to
be more efficient: looking up keys from values, or working with
subsets of the data.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top