Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #15591 > unrolled thread
| Started by | macm <moura.mario@gmail.com> |
|---|---|
| First post | 2011-11-11 05:31 -0800 |
| Last post | 2011-11-14 19:07 -0800 |
| Articles | 17 — 9 participants |
Back to article view | Back to comp.lang.python
Get keys from a dicionary macm <moura.mario@gmail.com> - 2011-11-11 05:31 -0800
Re: Get keys from a dicionary Jon Clements <joncle@googlemail.com> - 2011-11-11 08:09 -0800
Re: Get keys from a dicionary macm <moura.mario@gmail.com> - 2011-11-11 08:33 -0800
Re: Get keys from a dicionary macm <moura.mario@gmail.com> - 2011-11-11 08:38 -0800
Re: Get keys from a dicionary Dave Angel <d@davea.name> - 2011-11-11 11:47 -0500
Re: Get keys from a dicionary John Gordon <gordon@panix.com> - 2011-11-11 17:28 +0000
Re: Get keys from a dicionary John Gordon <gordon@panix.com> - 2011-11-11 16:25 +0000
Re: Get keys from a dicionary macm <moura.mario@gmail.com> - 2011-11-11 08:36 -0800
Re: Get keys from a dicionary Gelonida N <gelonida@gmail.com> - 2011-11-11 18:29 +0100
Re: Get keys from a dicionary Gelonida N <gelonida@gmail.com> - 2011-11-11 18:45 +0100
Re: Get keys from a dicionary John Gordon <gordon@panix.com> - 2011-11-11 17:51 +0000
Re: Get keys from a dicionary alex23 <wuwei23@gmail.com> - 2011-11-13 21:42 -0800
Re: Get keys from a dicionary alex23 <wuwei23@gmail.com> - 2011-11-13 21:44 -0800
Multilevel dicts/arrays v. tuples as keys? [Was: Re: Get keys from a dicionary] Matej Cepl <mcepl@redhat.com> - 2011-11-14 11:05 +0100
Re: Multilevel dicts/arrays v. tuples as keys? [Was: Re: Get keys from a dicionary] Tim Golden <mail@timgolden.me.uk> - 2011-11-14 10:42 +0000
Re: Multilevel dicts/arrays v. tuples as keys? Peter Otten <__peter__@web.de> - 2011-11-14 11:47 +0100
Re: Multilevel dicts/arrays v. tuples as keys? alex23 <wuwei23@gmail.com> - 2011-11-14 19:07 -0800
| From | macm <moura.mario@gmail.com> |
|---|---|
| Date | 2011-11-11 05:31 -0800 |
| Subject | Get keys from a dicionary |
| Message-ID | <8f5215a8-d08f-4355-a5a2-77fcaa32c92d@j10g2000vbe.googlegroups.com> |
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
[toc] | [next] | [standalone]
| From | Jon Clements <joncle@googlemail.com> |
|---|---|
| Date | 2011-11-11 08:09 -0800 |
| Message-ID | <1e00ab59-8fc5-4bd7-b52c-f98f3b0b4473@x8g2000yql.googlegroups.com> |
| In reply to | #15591 |
On Nov 11, 1:31 pm, macm <moura.ma...@gmail.com> wrote: > 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?
[toc] | [prev] | [next] | [standalone]
| From | macm <moura.mario@gmail.com> |
|---|---|
| Date | 2011-11-11 08:33 -0800 |
| Message-ID | <aac0b123-673b-4d8f-bc05-1f639515a951@c18g2000yqj.googlegroups.com> |
| In reply to | #15592 |
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
On Nov 11, 2:09 pm, Jon Clements <jon...@googlemail.com> wrote:
> On Nov 11, 1:31 pm, macm <moura.ma...@gmail.com> wrote:
>
> > 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?
[toc] | [prev] | [next] | [standalone]
| From | macm <moura.mario@gmail.com> |
|---|---|
| Date | 2011-11-11 08:38 -0800 |
| Message-ID | <c7364dd9-7c9b-45a5-a38a-e94a05541eee@w1g2000vba.googlegroups.com> |
| In reply to | #15594 |
Ok Sorry!!
Sorry the noise!!
def func(object):
print "%s" % object
Regards
On Nov 11, 2:33 pm, macm <moura.ma...@gmail.com> wrote:
> 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
>
> On Nov 11, 2:09 pm, Jon Clements <jon...@googlemail.com> wrote:
>
>
>
>
>
>
>
> > On Nov 11, 1:31 pm, macm <moura.ma...@gmail.com> wrote:
>
> > > 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?
[toc] | [prev] | [next] | [standalone]
| From | Dave Angel <d@davea.name> |
|---|---|
| Date | 2011-11-11 11:47 -0500 |
| Message-ID | <mailman.2647.1321030075.27778.python-list@python.org> |
| In reply to | #15594 |
On 11/11/2011 11:33 AM, macm wrote:
> 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.
--
DaveA
[toc] | [prev] | [next] | [standalone]
| From | John Gordon <gordon@panix.com> |
|---|---|
| Date | 2011-11-11 17:28 +0000 |
| Message-ID | <j9jm0k$e6n$1@reader1.panix.com> |
| In reply to | #15594 |
In <aac0b123-673b-4d8f-bc05-1f639515a951@c18g2000yqj.googlegroups.com> macm <moura.mario@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@panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
[toc] | [prev] | [next] | [standalone]
| From | John Gordon <gordon@panix.com> |
|---|---|
| Date | 2011-11-11 16:25 +0000 |
| Message-ID | <j9ji9f$69l$1@reader1.panix.com> |
| In reply to | #15591 |
In <8f5215a8-d08f-4355-a5a2-77fcaa32c92d@j10g2000vbe.googlegroups.com> macm <moura.mario@gmail.com> writes:
> 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
--
John Gordon A is for Amy, who fell down the stairs
gordon@panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
[toc] | [prev] | [next] | [standalone]
| From | macm <moura.mario@gmail.com> |
|---|---|
| Date | 2011-11-11 08:36 -0800 |
| Message-ID | <09bf2935-00e6-4ecb-a5fe-71566155f995@q16g2000yqn.googlegroups.com> |
| In reply to | #15593 |
On Nov 11, 2:25 pm, John Gordon <gor...@panix.com> wrote: > In <8f5215a8-d08f-4355-a5a2-77fcaa32c...@j10g2000vbe.googlegroups.com> macm <moura.ma...@gmail.com> writes: > > > 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 > > -- > John Gordon A is for Amy, who fell down the stairs > gor...@panix.com B is for Basil, assaulted by bears > -- Edward Gorey, "The Gashlycrumb Tinies" Hi John I am not a native English speaker. Sorry bad english. Regards macm
[toc] | [prev] | [next] | [standalone]
| From | Gelonida N <gelonida@gmail.com> |
|---|---|
| Date | 2011-11-11 18:29 +0100 |
| Message-ID | <mailman.2650.1321032617.27778.python-list@python.org> |
| In reply to | #15591 |
On 11/11/2011 02:31 PM, macm wrote:
> 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)
[toc] | [prev] | [next] | [standalone]
| From | Gelonida N <gelonida@gmail.com> |
|---|---|
| Date | 2011-11-11 18:45 +0100 |
| Message-ID | <mailman.2653.1321033516.27778.python-list@python.org> |
| In reply to | #15591 |
On 11/11/2011 02:31 PM, macm wrote:
> > 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)
[toc] | [prev] | [next] | [standalone]
| From | John Gordon <gordon@panix.com> |
|---|---|
| Date | 2011-11-11 17:51 +0000 |
| Message-ID | <j9jnbt$p0j$1@reader1.panix.com> |
| In reply to | #15602 |
In <mailman.2653.1321033516.27778.python-list@python.org> Gelonida N <gelonida@gmail.com> writes:
> > > There is a fast way (trick) to get k1 and k2 as string.
> > >
> > > Whithout loop all dict. Just it!
> 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.
--
John Gordon A is for Amy, who fell down the stairs
gordon@panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
[toc] | [prev] | [next] | [standalone]
| From | alex23 <wuwei23@gmail.com> |
|---|---|
| Date | 2011-11-13 21:42 -0800 |
| Message-ID | <fa9437c0-52db-49a4-a00d-f0a633468748@u24g2000pru.googlegroups.com> |
| In reply to | #15591 |
On Nov 11, 11:31 pm, macm <moura.ma...@gmail.com> wrote:
>
> 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.
[toc] | [prev] | [next] | [standalone]
| From | alex23 <wuwei23@gmail.com> |
|---|---|
| Date | 2011-11-13 21:44 -0800 |
| Message-ID | <f921ee23-9731-4909-946f-1da173917e09@f3g2000pri.googlegroups.com> |
| In reply to | #15591 |
On Nov 11, 11:31 pm, macm <moura.ma...@gmail.com> wrote:
>
> 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.
[toc] | [prev] | [next] | [standalone]
| From | Matej Cepl <mcepl@redhat.com> |
|---|---|
| Date | 2011-11-14 11:05 +0100 |
| Subject | Multilevel dicts/arrays v. tuples as keys? [Was: Re: Get keys from a dicionary] |
| Message-ID | <j9qp2t$1lnr$1@ns.felk.cvut.cz> |
| In reply to | #15591 |
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
[toc] | [prev] | [next] | [standalone]
| From | Tim Golden <mail@timgolden.me.uk> |
|---|---|
| Date | 2011-11-14 10:42 +0000 |
| Subject | Re: Multilevel dicts/arrays v. tuples as keys? [Was: Re: Get keys from a dicionary] |
| Message-ID | <mailman.2694.1321267380.27778.python-list@python.org> |
| In reply to | #15661 |
On 14/11/2011 10:05, Matej Cepl wrote: > 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
[toc] | [prev] | [next] | [standalone]
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2011-11-14 11:47 +0100 |
| Subject | Re: Multilevel dicts/arrays v. tuples as keys? |
| Message-ID | <mailman.2695.1321267697.27778.python-list@python.org> |
| In reply to | #15661 |
Matej Cepl wrote: > 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]
[toc] | [prev] | [next] | [standalone]
| From | alex23 <wuwei23@gmail.com> |
|---|---|
| Date | 2011-11-14 19:07 -0800 |
| Subject | Re: Multilevel dicts/arrays v. tuples as keys? |
| Message-ID | <74d33315-beb0-4b4e-90bb-0cac8c91c5e6@j19g2000pro.googlegroups.com> |
| In reply to | #15664 |
Peter Otten <__pete...@web.de> wrote: > 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.
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web