Re: newbie: dictionary - howto get key value
Joal Heagney wrote: > Does python guarantee that the lists given by phone.values() and > phone.keys() are in mutual order? Or is it possible that python will > return the lists in different orders for .values() and .keys()? Yes. Quoted from http://docs.python.org/lib/typesmapping.html: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". The same relationship holds for the iterkeys() and itervalues() methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same value for pairs. Another way to create the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]". Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
On Mon, 14 Mar 2005 05:02:25 GMT, Joal Heagney <[EMAIL PROTECTED]> wrote: >Tim Roberts wrote: >> "G. Völkl" <[EMAIL PROTECTED]> wrote: >> >>>I use a dictionary: >>> >>>phone = {'mike':10,'sue':8,'john':3} >>> >>>phone['mike'] --> 10 >>> >>>I want to know who has number 3? >>> >>>3 --> 'john' >>> >>>How to get it in the python way ? >> >> >> If you need to do this a lot, just keep two dictionaries, where the keys in >> each are the values in the other. >> >> reversephone = dict( zip( phone.values(), phone.keys() ) ) > >(Been away from python for a while, so forgive me if I'm asking a silly >question.) >Does python guarantee that the lists given by phone.values() and >phone.keys() are in mutual order? Or is it possible that python will >return the lists in different orders for .values() and .keys()? > Good question. I don't know. I hope so, but I would tend to write dict((v,k) for k,v in phone.items()) to do the equivalent, but note that it only works if everyone has a different phone number. >>> dict((v,k) for k,v in {'sue':3, 'bob':4}.items()) {3: 'sue', 4: 'bob'} >>> dict((v,k) for k,v in {'sue':3, 'bob':4, 'mike':4}.items()) {3: 'sue', 4: 'bob'} Surprised at who got left out? >>> {'sue':3, 'bob':4, 'mike':4}.items() [('sue', 3), ('mike', 4), ('bob', 4)] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
Tim Roberts wrote: "G. Völkl" <[EMAIL PROTECTED]> wrote: I use a dictionary: phone = {'mike':10,'sue':8,'john':3} phone['mike'] --> 10 I want to know who has number 3? 3 --> 'john' How to get it in the python way ? If you need to do this a lot, just keep two dictionaries, where the keys in each are the values in the other. reversephone = dict( zip( phone.values(), phone.keys() ) ) (Been away from python for a while, so forgive me if I'm asking a silly question.) Does python guarantee that the lists given by phone.values() and phone.keys() are in mutual order? Or is it possible that python will return the lists in different orders for .values() and .keys()? Joal -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
On Thu, 10 Mar 2005 18:56:41 +0100, bruno modulix <[EMAIL PROTECTED]> wrote: >G. Völkl wrote: >> Hello, >> >> I use a dictionary: >> >> phone = {'mike':10,'sue':8,'john':3} >> >> phone['mike'] --> 10 >> >> I want to know who has number 3? >> 3 --> 'john' > >Note that you can have many keys with the same value: >phone = {'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10} > > >> How to get it in the python way ? > >simplest way I could think of in 30': >def key_from_value(aDict, target): > return [key for key, value in aDict.items() if value==target] > >key_from_value(phone, 3) >--> ['john', 'jack'] > >but this is a linear search, so not very efficient if phone is big. >Then you may want to maintain a reversed index: >(here again, simplest way I could think of) > >def rev_index(aDict): > r = {} > for key, value in aDict.items(): > if r.has_key(value): > r[value].append(key) > else: > r[value] = [key] >return r >rev_phone = rev_index(phone) >rev_phone >--> {8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']} > >{8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']} > >rev_phone[3] >--> ['john', 'jack'] > >But now you've got another problem : you need to update the reversed >index each time you modify the dictionary... Which would lead to writing >a class extending dict, maintaining a reversed index, and exposing extra >methods to handle this. > Not very tested: < twoway.py > class Twoway(dict): def __setitem__(self, name, number): dict.__setitem__(self, name, number) self.setdefault(number, []).append(name) def __delitem__(self, name): num = self[name] dict.__delitem__(self, name) self[num].remove(name) if not self[num]: del self[num] def __init__(self, src=None): if src is None: return dict.__init__(self, src) for name, num in self.items(): self.setdefault(num, []).append(name) if __name__ == '__main__': phone = Twoway({'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10}) print 'jack:', phone['jack'] print 'same phone as jack:', phone[phone['jack']] print 'deleting jack ...'; del phone['jack'] print 'john:', phone['john'] print phone - [13:05] C:\pywk\sovm>py24 twoway.py jack: 3 same phone as jack: ['john', 'jack'] deleting jack ... john: 3 {'mike': 10, 3: ['john'], 8: ['sue'], 10: ['mike', 'helen'], 'sue': 8, 'helen': 10, 'john': 3} Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
John Machin wrote: G. Völkl wrote: I use a dictionary: phone = {'mike':10,'sue':8,'john':3} Of course in the real world using given name as a unique key is ludicrous: 'mike' is a.k.a. 'michael' (or 'mikhail' or 'michele' (which may be a typo for 'michelle')), and if there's only one 'sue' in your little black book you need to get out more :-) Maybe they're the names of his children... ;-) Of course, one could have multiple children with the same name under any or all of the following conditions: 1. insanity (perhaps of the parents or the children?) 2. remarriage (i.e. step-children) 3. sheer forgetfulness 4. laziness ("meet Brian, Brian, and Brian") This last is the closest I can come to making this post on-topic... sorry! :-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
bruno modulix wrote: > G. Völkl wrote: > > Hello, > > > > I use a dictionary: > > > > phone = {'mike':10,'sue':8,'john':3} > > > > phone['mike'] --> 10 > > > > I want to know who has number 3? > > 3 --> 'john' > > Note that you can have many keys with the same value: > phone = {'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10} Of course in the real world using given name as a unique key is ludicrous: 'mike' is a.k.a. 'michael' (or 'mikhail' or 'michele' (which may be a typo for 'michelle')), and if there's only one 'sue' in your little black book you need to get out more :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
"G. Völkl" <[EMAIL PROTECTED]> wrote: > >I use a dictionary: > >phone = {'mike':10,'sue':8,'john':3} > >phone['mike'] --> 10 > >I want to know who has number 3? > >3 --> 'john' > >How to get it in the python way ? If you need to do this a lot, just keep two dictionaries, where the keys in each are the values in the other. reversephone = dict( zip( phone.values(), phone.keys() ) ) -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > test = 3 #find person with this number > for x in xrange(len(phone.keys())): > print x >if phone[phone.keys()[x]] == test: > print phone.keys()[x] > break > >Being a newbie myself, I'd love a little critique on the above. Be kind Constructs like xrange(len(something)) are fairly typical for somone moving to Python from another language; usually there is a more idiomatic alternative. In this case, writing "for k in phone.keys()" would be a good start. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
[EMAIL PROTECTED] wrote: (top-post corrected) -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] n.org]On Behalf Of G. Völkl Sent: Thursday, March 10, 2005 12:19 PM To: python-list@python.org Subject: newbie: dictionary - howto get key value Hello, I use a dictionary: phone = {'mike':10,'sue':8,'john':3} phone['mike'] --> 10 I want to know who has number 3? 3 --> 'john' How to get it in the python way ? how about? test = 3 #find person with this number for x in xrange(len(phone.keys())): print x if phone[phone.keys()[x]] == test: print phone.keys()[x] break Being a newbie myself, I'd love a little critique on the above. 0/ does not retrieve all the information (just the first match) 1/ not reusable (hint : make it a function) 2/ does not retrieve the information, just print it 3/ also print some useless informations ('print x') 4/ makes len(phone.keys()) + 1 calls to phone.keys() hint : for key in phone.keys(): if phone[key] == test: print phone[key] or better: for key, value in phone.items(): if value == test: print key Be kind as I don't know what else needs to be done in Gerhard's process. Hope I haven't been to harsh !-) Of course, we could put this loop in a call and return the name yeps. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
G. Völkl wrote: Hello, I use a dictionary: phone = {'mike':10,'sue':8,'john':3} phone['mike'] --> 10 I want to know who has number 3? 3 --> 'john' How to get it in the python way ? Thanks Gerhard How 'bout a list comprehension: In [1]:phone = {'mike':10,'sue':8,'john':3, 'billy':3} In [2]:phone.items() Out[2]:[('billy', 3), ('mike', 10), ('john', 3), ('sue', 8)] In [3]:[i[0] for i in phone.items() if i[1] == 3] Out[3]:['billy', 'john'] I added an additional person named "billy" with a number of 3 since values in a dictionary don't have to be unique. Jeremy Jones -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
G. Völkl wrote: Hello, I use a dictionary: phone = {'mike':10,'sue':8,'john':3} phone['mike'] --> 10 I want to know who has number 3? 3 --> 'john' Note that you can have many keys with the same value: phone = {'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10} How to get it in the python way ? simplest way I could think of in 30': def key_from_value(aDict, target): return [key for key, value in aDict.items() if value==target] key_from_value(phone, 3) --> ['john', 'jack'] but this is a linear search, so not very efficient if phone is big. Then you may want to maintain a reversed index: (here again, simplest way I could think of) def rev_index(aDict): r = {} for key, value in aDict.items(): if r.has_key(value): r[value].append(key) else: r[value] = [key] return r rev_phone = rev_index(phone) rev_phone --> {8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']} {8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']} rev_phone[3] --> ['john', 'jack'] But now you've got another problem : you need to update the reversed index each time you modify the dictionary... Which would lead to writing a class extending dict, maintaining a reversed index, and exposing extra methods to handle this. But there may be a better way (someone else ?) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: dictionary - howto get key value
phone = {'mike':10,'sue':8,'john':3} print [key for key, value in phone.items() if value == 3] -> ['john'] -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
RE: newbie: dictionary - howto get key value
how about? test = 3 #find person with this number for x in xrange(len(phone.keys())): print x if phone[phone.keys()[x]] == test: print phone.keys()[x] break Being a newbie myself, I'd love a little critique on the above. Be kind as I don't know what else needs to be done in Gerhard's process. Of course, we could put this loop in a call and return the name -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] n.org]On Behalf Of G. Völkl Sent: Thursday, March 10, 2005 12:19 PM To: python-list@python.org Subject: newbie: dictionary - howto get key value Hello, I use a dictionary: phone = {'mike':10,'sue':8,'john':3} phone['mike'] --> 10 I want to know who has number 3? 3 --> 'john' How to get it in the python way ? Thanks Gerhard -- http://mail.python.org/mailman/listinfo/python-list ___ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. -- http://mail.python.org/mailman/listinfo/python-list