Re: A basic dictionary question
David Aldrich wrote: Hi I am fairly new to Python. I am writing some code that uses a dictionary to store definitions of hardware registers. Here is a small part of it: import sys register = { 'address' : 0x3001c, 'fields' : { 'FieldA' : { 'range' : (31,20), }, 'FieldB' : { 'range' : (19,16), }, }, 'width' : 32 }; def main(): fields = register['fields'] for field, range_dir in fields: == This line fails range_dir = field['range'] x,y = range_dir['range'] print(x, y) if __name__ == '__main__': main() I want the code to print the range of bits of each field defined in the dictionary. The output is: Traceback (most recent call last): File testdir.py, line 32, in module main() File testdir.py, line 26, in main for field, range_dir in fields: ValueError: too many values to unpack (expected 2) Please will someone explain what I am doing wrong? for key in some_dict: ... iterates over the keys of the dictionary, for (key, value) pairs you need for key, value in some_dict.items(): ... Also I would like to ask how I could print the ranges in the order they are defined. Should I use a different dictionary class or could I add a field to the dictionary/list to achieve this? Have a look at collections.OrderedDict: https://docs.python.org/dev/library/collections.html#collections.OrderedDict If you don't care about fast access by key you can also use a list of (key, value) pairs. -- https://mail.python.org/mailman/listinfo/python-list
Re: A basic dictionary question
On 2015-06-11 11:10, David Aldrich wrote: Hi I am fairly new to Python. I am writing some code that uses a dictionary to store definitions of hardware registers. Here is a small part of it: import sys register = { 'address' : 0x3001c, 'fields' : { 'FieldA' : { 'range' : (31,20), }, 'FieldB' : { 'range' : (19,16), }, }, 'width' : 32 }; def main(): fields = register['fields'] for field, range_dir in fields: == This line fails range_dir = field['range'] x,y = range_dir['range'] print(x, y) if __name__ == '__main__': main() I want the code to print the range of bits of each field defined in the dictionary. The output is: Traceback (most recent call last): File testdir.py, line 32, in module main() File testdir.py, line 26, in main for field, range_dir in fields: ValueError: too many values to unpack (expected 2) Please will someone explain what I am doing wrong? You're iterating over the keys. What you want is to iterate over fields.items() which gives the key/value pairs. Also I would like to ask how I could print the ranges in the order they are defined. Should I use a different dictionary class or could I add a field to the dictionary/list to achieve this? Dicts are unordered. Try 'OrderedDict' from the 'collections' module. -- https://mail.python.org/mailman/listinfo/python-list
A basic dictionary question
Hi I am fairly new to Python. I am writing some code that uses a dictionary to store definitions of hardware registers. Here is a small part of it: import sys register = { 'address' : 0x3001c, 'fields' : { 'FieldA' : { 'range' : (31,20), }, 'FieldB' : { 'range' : (19,16), }, }, 'width' : 32 }; def main(): fields = register['fields'] for field, range_dir in fields: == This line fails range_dir = field['range'] x,y = range_dir['range'] print(x, y) if __name__ == '__main__': main() I want the code to print the range of bits of each field defined in the dictionary. The output is: Traceback (most recent call last): File testdir.py, line 32, in module main() File testdir.py, line 26, in main for field, range_dir in fields: ValueError: too many values to unpack (expected 2) Please will someone explain what I am doing wrong? Also I would like to ask how I could print the ranges in the order they are defined. Should I use a different dictionary class or could I add a field to the dictionary/list to achieve this? Best regards David -- https://mail.python.org/mailman/listinfo/python-list
Basic list/dictionary question
Greetings, I'm trying to categorize items in a list, by copying them into a dictionary... A simple example with strings doesn't seem to work how I'd expect: basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] d = {} d = d.fromkeys(basket, []) d {'orange': [], 'pear': [], 'apple': [], 'banana': []} for fruit in basket: ... d[fruit].append(fruit) ... No if I print d I'd EXPECT d {'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple', 'apple'], 'banana': ['banana']} But what I GET is d {'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']} From what I can work out, there is only ONE list that is referenced from the dictionary 4 times. Which would be because the *same empty list* is assigned to every key in the dictionary by the fromkeys line. But that seems *seriously *counter-intuitive to me... Would anyone beg to differ and try to rewire my thinking? (I'm from a Java background if that helps) I've already solved the problem a different way, but I am concerned about this counter-intuitiveness as I see it. rgds, Daniel Jowett -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic list/dictionary question
On Wed, Nov 11, 2009 at 4:16 AM, Daniel Jowett daniel.jow...@gmail.com wrote: Greetings, I'm trying to categorize items in a list, by copying them into a dictionary... A simple example with strings doesn't seem to work how I'd expect: basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] d = {} d = d.fromkeys(basket, []) d {'orange': [], 'pear': [], 'apple': [], 'banana': []} for fruit in basket: ... d[fruit].append(fruit) ... No if I print d I'd EXPECT d {'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple', 'apple'], 'banana': ['banana']} But what I GET is d {'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']} From what I can work out, there is only ONE list that is referenced from the dictionary 4 times. Which would be because the same empty list is assigned to every key in the dictionary by the fromkeys line. But that seems seriously counter-intuitive to me... Python doesn't do any extra copying in most places unless you /explicitly/ do so yourself or ask it to; so yes, in this case, Python just copies references to the same object and does not copy the object itself. You'd probably be better off using a defaultdict in your particular usecase: http://docs.python.org/library/collections.html#collections.defaultdict Or and so you avoid running into it, default argument values aren't copied either: In [2]: def foo(z, a=[]): ...: a.append(z) ...: return a ...: In [3]: foo(1) Out[3]: [1] In [4]: foo(2) Out[4]: [1, 2] In [5]: foo(2) Out[5]: [1, 2, 2] In [6]: foo(3) Out[6]: [1, 2, 2, 3] In [7]: foo(4,[]) Out[7]: [4] In [8]: foo(5) Out[8]: [1, 2, 2, 3, 5] Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic list/dictionary question
Thanks Chris, yes it's becoming clearer now. And defaultdict looks nice - unfortunately I'm stuck to python 2.4 as I'm using Plone. Thanks again, Daniel 2009/11/11 Chris Rebert c...@rebertia.com On Wed, Nov 11, 2009 at 4:16 AM, Daniel Jowett daniel.jow...@gmail.com wrote: Greetings, I'm trying to categorize items in a list, by copying them into a dictionary... A simple example with strings doesn't seem to work how I'd expect: basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] d = {} d = d.fromkeys(basket, []) d {'orange': [], 'pear': [], 'apple': [], 'banana': []} for fruit in basket: ... d[fruit].append(fruit) ... No if I print d I'd EXPECT d {'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple', 'apple'], 'banana': ['banana']} But what I GET is d {'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']} From what I can work out, there is only ONE list that is referenced from the dictionary 4 times. Which would be because the same empty list is assigned to every key in the dictionary by the fromkeys line. But that seems seriously counter-intuitive to me... Python doesn't do any extra copying in most places unless you /explicitly/ do so yourself or ask it to; so yes, in this case, Python just copies references to the same object and does not copy the object itself. You'd probably be better off using a defaultdict in your particular usecase: http://docs.python.org/library/collections.html#collections.defaultdict Or and so you avoid running into it, default argument values aren't copied either: In [2]: def foo(z, a=[]): ...: a.append(z) ...: return a ...: In [3]: foo(1) Out[3]: [1] In [4]: foo(2) Out[4]: [1, 2] In [5]: foo(2) Out[5]: [1, 2, 2] In [6]: foo(3) Out[6]: [1, 2, 2, 3] In [7]: foo(4,[]) Out[7]: [4] In [8]: foo(5) Out[8]: [1, 2, 2, 3, 5] Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic list/dictionary question
On Nov 11, 8:58 pm, Chris Rebert c...@rebertia.com wrote: On Wed, Nov 11, 2009 at 4:16 AM, Daniel Jowett daniel.jow...@gmail.com wrote: Greetings, I'm trying to categorize items in a list, by copying them into a dictionary... A simple example with strings doesn't seem to work how I'd expect: basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] d = {} d = d.fromkeys(basket, []) d {'orange': [], 'pear': [], 'apple': [], 'banana': []} for fruit in basket: ... d[fruit].append(fruit) ... No if I print d I'd EXPECT d {'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple', 'apple'], 'banana': ['banana']} But what I GET is d {'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']} From what I can work out, there is only ONE list that is referenced from the dictionary 4 times. Which would be because the same empty list is assigned to every key in the dictionary by the fromkeys line. But that seems seriously counter-intuitive to me... Python doesn't do any extra copying in most places unless you /explicitly/ do so yourself or ask it to; so yes, in this case, Python just copies references to the same object and does not copy the object itself. You'd probably be better off using a defaultdict in your particular usecase:http://docs.python.org/library/collections.html#collections.defaultdict Or and so you avoid running into it, default argument values aren't copied either: In [2]: def foo(z, a=[]): ...: a.append(z) ...: return a ...: In [3]: foo(1) Out[3]: [1] In [4]: foo(2) Out[4]: [1, 2] In [5]: foo(2) Out[5]: [1, 2, 2] In [6]: foo(3) Out[6]: [1, 2, 2, 3] In [7]: foo(4,[]) Out[7]: [4] In [8]: foo(5) Out[8]: [1, 2, 2, 3, 5] Cheers, Chris --http://blog.rebertia.com Usefull! -- http://mail.python.org/mailman/listinfo/python-list
Re: Another Dictionary Question
On 9 fév, 04:02, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 08 Feb 2007 23:32:50 -0300, Sick Monkey [EMAIL PROTECTED] escribió: db = {'[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none',} And I want to pull out all of the gmail.com addresses.. How would I do this? NOTE: I already have a regular expression to search for this, but I feel that looping over a dictionary is not very efficient. (answer to the OP) Looping over a dict keys should be quite fast. If you're worried about perfs, it would be better to first get rid of useless regexps: filtered_db = dict((k, v) for k, v in db.iteritems() \ if not k.endswith('@gmail.com')) -- http://mail.python.org/mailman/listinfo/python-list
Another Dictionary Question
Hello All. I have a question concerning searching data within dictionaries. Lets say I have a dictionary called db. db = {'[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none',} And I want to pull out all of the gmail.com addresses.. How would I do this? NOTE: I already have a regular expression to search for this, but I feel that looping over a dictionary is not very efficient. So I have: domsrch = re.compile(r@(\S+)) listToLookFor = ['gmail.com'] db = {'[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none',} I wonder if there is a way to do something like Psuedo code for item in listToLookFor: if domsrch.findall(db.has_key( item )): print horray NOTE: I know the findall is for lists, but I dont know of an efficient way to search for this in a dictionary. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another Dictionary Question
En Thu, 08 Feb 2007 23:32:50 -0300, Sick Monkey [EMAIL PROTECTED] escribió: db = {'[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none',} And I want to pull out all of the gmail.com addresses.. How would I do this? NOTE: I already have a regular expression to search for this, but I feel that looping over a dictionary is not very efficient. for key in db: if domain_regexp.search(key): print horray Iterating over the dictionary keys should be rather efficient. timeit and see if it worths to make it more complex. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Another Dictionary Question
At Friday 9/2/2007 00:50, you wrote: Hey Gabriel, Please keep posting on the list - you'll reach a whole lot of people there... Thanks again for the help... but im still having some issues. For some reason the domsrch.search(key) is pointing to a memory reference... so when I do this: [...] print domsrch.search(key) if domain == domsrch.search(key): utp.write(key + '\n') _sre.SRE_Match object at 0xb7f7b0e0 This is the standard str()/repr() of an object that doesn't care to provide it's own __str__/__repr__ method. Let's look at the docs. From http://docs.python.org/lib/re-objects.html we see that the search() method returns a MatchObject. And what's that...? See http://docs.python.org/lib/match-objects.html , you might be interested in using group(1) But doing the search that way, means that you must traverse the dict many times, once per domain searched. Doesn't look so good. Two approaches: 1) Build a specific re that matches exactly all the domains you want (and not others). This way you don't even need to use any method in the returned MatchObject: simply, if it's not None, there was a match. Something like this: code domains = [yahoo.com, google.com, gmail.com] domainsre = |.join([(%s) % re.escape(@+domain)]) # that means: put an @ in front of each domain, make it a group, and join all groups with | # ([EMAIL PROTECTED])|([EMAIL PROTECTED])|([EMAIL PROTECTED]) domsrch = re.compile(domainsre, re.IGNORECASE) for key in d1: if domsrch.search(key): print key /code 2) Forget about regular expressions; you already know they're email addresses, just split on the @ and check the right side against the desired domains: code domains = [yahoo.com, google.com, gmail.com] domainsSet = set(domains) for key in d1: name, domain = key.split(@,1) if domain.lower() in domainsSet: print key /code -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
newbie: datastructure `dictionary' question
Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. I am trying to fill a nested dictionary from parsing a logfile. However each time there is only one key entry created and that's it. Just one entry, while the keys are different. That's 100% sure. I think therefore that it is an assignment error in my part. [there we have it...] To give an static example of the datastructure that I am using to clear any confusion on the datastructure part: records = { 'fam/jason-a' : { 'date': 'Fri Sep 8 16:45:55 2006', 'from': 'jason', 'subject' : 'Re: Oh my goes.', 'msize' : '237284' }, 'university/solar-system' : { 'date': 'Fri Sep 8 16:45:46 2006', 'from': 'jd', 'subject' : 'Vacancies for students', 'msize' : '9387' } } Looping over this datastructure is no problem. rkeys = ['date', 'from', 'subject', 'msize'] for folder in records.keys(): print '--' print folder for key in rkeys: print records[folder][key] Now for the actual program/dynamic part - assignment in the loop I use the following function. Note `datum' is not a date object, just a string. def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): str = line.strip() if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom elif str[:4] == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} else: other += 1 displrec(records) Note, this is not ment as a collision type datastructure, all initial data entries are unique. My question: Where is my assignment e.g. records = {folder wrong ? Thankx in advance for any tips, hints and answers. Cheers, Jason. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
jason schrieb: Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. I am trying to fill a nested dictionary from parsing a logfile. However each time there is only one key entry created and that's it. Just one entry, while the keys are different. That's 100% sure. I think therefore that it is an assignment error in my part. [there we have it...] To give an static example of the datastructure that I am using to clear any confusion on the datastructure part: records = { 'fam/jason-a' : { 'date': 'Fri Sep 8 16:45:55 2006', 'from': 'jason', 'subject' : 'Re: Oh my goes.', 'msize' : '237284' }, 'university/solar-system' : { 'date': 'Fri Sep 8 16:45:46 2006', 'from': 'jd', 'subject' : 'Vacancies for students', 'msize' : '9387' } } Looping over this datastructure is no problem. rkeys = ['date', 'from', 'subject', 'msize'] for folder in records.keys(): print '--' print folder for key in rkeys: print records[folder][key] Now for the actual program/dynamic part - assignment in the loop I use the following function. Note `datum' is not a date object, just a string. def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): str = line.strip() if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom elif str[:4] == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} else: other += 1 displrec(records) Note, this is not ment as a collision type datastructure, all initial data entries are unique. My question: Where is my assignment e.g. records = {folder wrong ? What you essentially do is this: records = {some : dict} records = {some other : dict} You rebind the name records to a new dictionary. So all your previously stored data is garbage collected. What you most probably want to do (I'm a bit confused about your code too lazy to dig deeper): records = {} records[folder] = {'date' : ...} Notice that the dict[key]=value syntax mutates the existing dictionary. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
jason wrote: Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. I am trying to fill a nested dictionary from parsing a logfile. However each time there is only one key entry created and that's it. Just one entry, while the keys are different. That's 100% sure. I think therefore that it is an assignment error in my part. [there we have it...] To give an static example of the datastructure that I am using to clear any confusion on the datastructure part: records = { 'fam/jason-a' : { 'date': 'Fri Sep 8 16:45:55 2006', 'from': 'jason', 'subject' : 'Re: Oh my goes.', 'msize' : '237284' }, 'university/solar-system' : { 'date': 'Fri Sep 8 16:45:46 2006', 'from': 'jd', 'subject' : 'Vacancies for students', 'msize' : '9387' } } Looping over this datastructure is no problem. rkeys = ['date', 'from', 'subject', 'msize'] for folder in records.keys(): print '--' print folder for key in rkeys: print records[folder][key] Now for the actual program/dynamic part - assignment in the loop I use the following function. Note `datum' is not a date object, just a string. def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): str = line.strip() if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom elif str[:4] == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} You are *assigning* records = blahblah each time around. records will end up being bound to the blahblah related to the *last* record that you read. You can do it item by item: records[folder]['date'] = datum etc or as a oneliner: records[folder] = {'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1} When you find yourself using a dictionary with constant keys like 'date', it's time to start thinking OO. class LogMessage(object): def __init__(self, date, .) self.date = date etc then later: records[folder] = LogMessage( date=datum, mesgbytes= extrmsize(str[8:]), mesgcount=1, ) [snip] HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
On Sat, 09 Sep 2006 09:00:35 -0700, John Machin wrote: jason wrote: Hello, I am completely new to python and I have question that I unfortunately could not find in the various documentation online. My best guess is that the answer should be quitte easy but I have just enterd the learning phase so that means a hightend chance for stupidity and mistakes on my part. cut ... /cut Owww.. Of course... ! Thankx for the answer and the suggestion. It really helped me a lot. I defintely going to take the OO approach later on. thankx again for the quick reply. Jason. You are *assigning* records = blahblah each time around. records will end up being bound to the blahblah related to the *last* record that you read. You can do it item by item: records[folder]['date'] = datum etc or as a oneliner: records[folder] = {'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1} When you find yourself using a dictionary with constant keys like 'date', it's time to start thinking OO. class LogMessage(object): def __init__(self, date, .) self.date = date etc then later: records[folder] = LogMessage( date=datum, mesgbytes= extrmsize(str[8:]), mesgcount=1, ) [snip] HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: datastructure `dictionary' question
jason a écrit : Just some more suggestions: def parselog(data): other = 0 records = {} for line in string.split(data, '\n'): for line in data.split('\n'): str = line.strip() This will shadow the builtin 'str' type. You could reassign to 'line' instead, or manage to get stripped lines already: for line in map(str.strip, data.split('\n'): if str[:4] == 'From': mfrom, datum = extrfrom(str), extrdate(str) print datum, mfrom Mixing processing with IO may not be a good idea... elif str[:4] == 'Fold': line_type = line[:4] if line_type == 'From': # code here elif line_type == 'Fold': folder = extrfolder(str[8:]) records = {folder : { 'date' : datum, 'mesgbytes' : extrmsize(str[8:]), 'mesgcount' : 1}} You now know that it should be: records[folder] = {...} else: other += 1 displrec(records) As a last note, you may want to pay more attention to your namings... ie, 'display_records()' is much more readable than 'displrec()' and still not to long to type !-) My 2 cents (and a half) -- http://mail.python.org/mailman/listinfo/python-list
Dictionary question
Hi I have written the following which works, but I would like to write it less clumsy. I have a dictionary in which I loop through the keys for a dynamic programming algorithm. If a key is present I test if its value is better than the current, if it is not present I just create it. Would it be possible to write it more compact? ###3 c=1 s=8 x=2 l=list() l.append(dict()) l[0][5]=0 l.append(dict()) for a, e in l[-2].iteritems(): if a+cs: # Can this improved? if a+c in l[-1]: # if l[-1][a+c]x+e: # l[-1][a+c]=x+e # else: # l[-1][a+c]=x+e # print l # tia, -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question
Brian Elmegaard [EMAIL PROTECTED] writes: At least it was clumsy to post a wrong example. This shows what = find clumsy. c=1 x=2 l=list() l.append(dict()) l[0][5]=0 l.append(dict()) for a, e in l[-2].iteritems(): # Can this be written better? if a+c in l[-1]: if l[-1][a+c]x+e: l[-1][a+c]=x+e else: l[-1][a+c]=x+e # print l Hi I have written the following which works, but I would like to write it less clumsy. I have a dictionary in which I loop through the keys for a dynamic programming algorithm. If a key is present I test if its value is better than the current, if it is not present I just create it. Would it be possible to write it more compact? ###3 c=1 s=8 x=2 l=list() l.append(dict()) l[0][5]=0 l.append(dict()) for a, e in l[-2].iteritems(): if a+cs: # Can this improved? if a+c in l[-1]: # if l[-1][a+c]x+e: # l[-1][a+c]=x+e # else: # l[-1][a+c]=x+e # print l # tia, -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question
Brian, You can try the setdefault method of the dictionary. For a dictionary D the setdefault work like this: D.setdefault(k, defvalue). If k not in D then D[k] is set to defvalue and defvalue is returned. For example: In [1]: d={} In [2]: d.setdefault(1,5) Out[2]:5 In [3]: d Out[3]:{1: 5} In your case you could do something like: if l[-1].setdefault(a+c, x+e)x+e: l[-1][a+c]=x+e If a+c not in l[-1] then it the if ... line will set it to x+e and x+e will be returned, obviously the if ... will fail and the execution will go on after the if block. If a+c is in l[-1] then if will compare l[-1][a+c] to x+e. Also for clarity you might actually want to assign some variables to a+c and x+e since you repeat them so often. That actually might speed up your code a little too, but don't do it just for a minor speedup do it for clarity and simplicity most of all! Good luck, Nick Vatamaniuc Brian Elmegaard wrote: Brian Elmegaard [EMAIL PROTECTED] writes: At least it was clumsy to post a wrong example. This shows what = find clumsy. c=1 x=2 l=list() l.append(dict()) l[0][5]=0 l.append(dict()) for a, e in l[-2].iteritems(): # Can this be written better? if a+c in l[-1]: if l[-1][a+c]x+e: l[-1][a+c]=x+e else: l[-1][a+c]=x+e # print l Hi I have written the following which works, but I would like to write it less clumsy. I have a dictionary in which I loop through the keys for a dynamic programming algorithm. If a key is present I test if its value is better than the current, if it is not present I just create it. Would it be possible to write it more compact? ###3 c=1 s=8 x=2 l=list() l.append(dict()) l[0][5]=0 l.append(dict()) for a, e in l[-2].iteritems(): if a+cs: # Can this improved? if a+c in l[-1]: # if l[-1][a+c]x+e: # l[-1][a+c]=x+e # else: # l[-1][a+c]=x+e # print l # tia, -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question
Brian Elmegaard wrote: for a, e in l[-2].iteritems(): # Can this be written better? if a+c in l[-1]: if l[-1][a+c]x+e: l[-1][a+c]=x+e else: l[-1][a+c]=x+e # I'd start with something like for a, e in l[-2].iteritems(): keytotal = a+c valtotal = x+e last = l[-1] if keytotal in last: if last[keytotal] valtotal: last[keytotal] = valtotal else: last[keytotal] = valtotal Could probably simplify that even more by using min(), but I don't know what kind of data you are expecting last[keytotal] = min(last.get(keytotal), valtotal) comes close to working - it would if you were doing max. -- - Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question
On 18/07/2006 9:51 PM, Brian Elmegaard wrote: Brian Elmegaard [EMAIL PROTECTED] writes: At least it was clumsy to post a wrong example. This shows what = find clumsy. c=1 x=2 l=list() l.append(dict()) l[0][5]=0 l.append(dict()) for a, e in l[-2].iteritems(): # Can this be written better? Definitely. 1. Use meaningful names. Especially don't use 'L'.lower() as it's too easily confused with the digit '1'. 2. Put spaces around operators -- in general, RTFStyleGuide http://www.python.org/dev/peps/pep-0008 3. When you find yourself typing the same expression 4 times, it's time to give it a name of its own (or to throw away a usage or two). if a+c in l[-1]: if l[-1][a+c]x+e: l[-1][a+c]=x+e else: l[-1][a+c]=x+e Here's a start. Only you know what *really* meaningful names you should be using. mykey = a + c newvalue = x + e lastdict = dictlist[-1] if mykey not in lastdict or lastdict[mykey] newvalue: lastdict[mykey] = newvalue 4. Add some comments about what you are trying to achieve. What is the point of keeping the two dicts in a list??? Can't you give them names, like rawdatadict and maxdict? HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question
John Machin [EMAIL PROTECTED] writes: 2. Put spaces around operators -- in general, RTFStyleGuide http://www.python.org/dev/peps/pep-0008 I din't know it. Thanks. Only you know what *really* meaningful names you should be using. I have better names in my running code. mykey = a + c newvalue = x + e lastdict = dictlist[-1] if mykey not in lastdict or lastdict[mykey] newvalue: lastdict[mykey] = newvalue Better, thanks. 4. Add some comments about what you are trying to achieve. What is the point of keeping the two dicts in a list??? Can't you give them names, like rawdatadict and maxdict? It's a dynamic programming problem, so this will contain as many dicts as hours in the year. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question
Justin Azoff [EMAIL PROTECTED] writes: last[keytotal] = min(last.get(keytotal), valtotal) comes close to working - it would if you were doing max. Thanks, I think this would help. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question
Nick Vatamaniuc [EMAIL PROTECTED] writes: if l[-1].setdefault(a+c, x+e)x+e: l[-1][a+c]=x+e Thanks for the answer. I will try it. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Notice the dictionary is only changed if the key was missing. a = {} a.setdefault(a, 1) '1' a.setdefault(a, 2) '1' a.setdefault(b, 3) '3' a {'a': '1', 'b': '3'} a.setdefault(a, 5) '1' a {'a': '1', 'b': '3'} -Jim On 7/11/05, Peter Hansen [EMAIL PROTECTED] wrote: Ric Da Force wrote: How does setdefault work exactly? I am looking in the docs and can't figure it out... If the key (the first argument) already exists in the dictionary, the corresponding value is returned. If the key does not exist in the dictionary, it is stored in the dictionary and bound to the second argument, and then that second argument is returned as the value. (I always have to ignore the name to think about how it works, or it gets in the way of my understanding it. The name makes fairly little sense to me.) -Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
(Fixed top-posting) James Carroll wrote: On 7/11/05, Peter Hansen [EMAIL PROTECTED] wrote: (I always have to ignore the name to think about how it works, or it gets in the way of my understanding it. The name makes fairly little sense to me.) Notice the dictionary is only changed if the key was missing. James, I'll assume your reply was intended to address my comment above. It's not so much that the concept of set the default value for this key is poorly captured by the name setdefault, but that the function is used almost exclusively in the idiom below, where it is critical that it also _returns_ the value, which is usually then operated on immediately, usually in the same line of code. dict.setdefault(key, defaultValue).someMethodOnKey() or dict.setdefault(key, defaultValue) #= value, where # is some operator. I suppose I shouldn't blame setdefault() itself for being poorly named, but it's confusing to me each time I see it in the above, because the name doesn't emphasize that the value is being returned, and yet that fact is arguably more important than the fact that a default is set! I can't think of a better name, though, although I might find foo less confusing in the above context. :-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Oops.. Gmail just normally puts the reply to at the bottom of the discussion... so by default I reply to the list, and the last person to post. My comment was not directed at you. I just posted the contents of an interactive session that I did to better understand setdefault myself. I've got to remind myself to change the reply-to address to the list. (other lists do this by default, why not this one?) I agree that the name doesn't ring quite right to me either. I kind of understand what the creator of the function was getting at... it's kind of like when you want to retrieve a configuration variable from a container, but if it's not there, then you want to use a default: storedWidth = container.GetConfigurationValue(name = width, default=500) If there is a width stored, it will retrieve that, otherwise it will give you the default that you specified in the second parameter. It makes it easier than checking for existance, then retrieving or assigning a default. Setdefault, in my mind is really a _get_ kind of operation. It retrieves from the dictionary most of the time, and only does anything different when the key doesn't exist, and then does an assignment... so my next guess at a better name for setdefault would be: value = container.GetOrAddDefault(key=a, default=[]) value.append(listvalue) but that's kind of confusing too, but it better describes what is happening. -Jim On 7/12/05, Peter Hansen [EMAIL PROTECTED] wrote: (Fixed top-posting) James Carroll wrote: On 7/11/05, Peter Hansen [EMAIL PROTECTED] wrote: (I always have to ignore the name to think about how it works, or it gets in the way of my understanding it. The name makes fairly little sense to me.) Notice the dictionary is only changed if the key was missing. James, I'll assume your reply was intended to address my comment above. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
[Peter Hansen] ... I suppose I shouldn't blame setdefault() itself for being poorly named, No, you should blame Guido for that wink. but it's confusing to me each time I see it in the above, because the name doesn't emphasize that the value is being returned, and yet that fact is arguably more important than the fact that a default is set! I can't think of a better name, though, although I might find foo less confusing in the above context. :-) I wanted to call it getorset() -- so much so that even now I sometimes still type that instead! The get part reminds me that it's fetching a value, same as dict.get(key, default) -- or set'ing it too if there's not already a value to get. If you have a fancy enough editor, you can teach it to replace setdefault by getorset whenever you type the former ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
On Tue, 12 Jul 2005 11:52:41 -0400, Tim Peters [EMAIL PROTECTED] wrote: [Peter Hansen] ... I suppose I shouldn't blame setdefault() itself for being poorly named, No, you should blame Guido for that wink. but it's confusing to me each time I see it in the above, because the name doesn't emphasize that the value is being returned, and yet that fact is arguably more important than the fact that a default is set! I can't think of a better name, though, although I might find foo less confusing in the above context. :-) I wanted to call it getorset() -- so much so that even now I sometimes still type that instead! The get part reminds me that it's fetching a value, same as dict.get(key, default) -- or set'ing it too if there's not already a value to get. If you have a fancy enough editor, you can teach it to replace setdefault by getorset whenever you type the former ;-) But it isn't get OR set, it's set_default_if_no_value_then_either_way_effectively_get ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Tricky Dictionary Question from newbie
Hi all, I have a dictionary containing about 300 items, some of the values being repeated. Both keys and values are strings. How can I turn this thing on its head so that we create a key based on each unique value and build the values based on the keys corresponding to the repeated values? It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} I am still learning Python and have struggled with this for hours before deciding to go for help. Unfortunately, I didn't really know how to search for this in google and decided to post it here. I apologise if this is too basic for this newsgroup... Ric -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Hello, Try that, it may not be the better solution, but it seems to work: #def invertDict(d): # d2 = {} # for k, v in d.iteritems(): # d2.setdefault(v, []).append(k) # return d2 Cyril On 7/11/05, Ric Da Force [EMAIL PROTECTED] wrote: Hi all,I have a dictionary containing about 300 items, some of the values beingrepeated.Both keys and values are strings.How can I turn this thing onits head so that we create a key based on each unique value and build the values based on the keys corresponding to the repeated values?It is hard to explain but this is what I mean:Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This isnot'}I want this to return a new dict with string keys and lists containing the previous keys for repeated values.NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']}I am still learning Python and have struggled with this for hours beforedeciding to go for help.Unfortunately, I didn't really know how to search for this in google and decided to post it here.I apologise if this is toobasic for this newsgroup...Ric--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Hi! Dict = {'rt': 'repeated', 'sr':'repeated', 'gf':'not repeated'} NewDic = {} for k,v in Dict.items(): NewDic.setdefault(v, []).append(k) Regards, mawe -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Hum... I think an iteritems is better, this way, python don't need to create in memory a complete list of couple key, value.On 7/11/05, Markus Weihs [EMAIL PROTECTED] wrote: Hi! Dict = {'rt': 'repeated', 'sr':'repeated', 'gf':'not repeated'} NewDic = {} for k,v in Dict.items(): NewDic.setdefault(v, []).append(k)Regards, mawe-- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Ric Da Force [EMAIL PROTECTED] writes: It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} NewDict = {} for x in Dict.keys(): try: NewDict[Dict[x]].append(x) except KeyError: NewDict[Dict[x]] = [x] -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson It is difficult for men in high office to avoid the malady of self-delusion.- Calvin Coolidge -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Mark Jackson wrote: Ric Da Force [EMAIL PROTECTED] writes: It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} NewDict = {} for x in Dict.keys(): try: NewDict[Dict[x]].append(x) except KeyError: NewDict[Dict[x]] = [x] Or, more up-to-date: NewDict = {} for key, val in Dict.iteritems(): NewDict.setdefault(val, []).append(key) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Thank you guys! (Reinhold, Mark and Markus) I must confess that I am absolutely awe struck at the power of this language! There is no way in the world that I would have envisaged such simple and elegant solutions!!! Reinhold, is your solution specific to 2.4? Kind Regards, Ric Reinhold Birkenfeld [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Mark Jackson wrote: Ric Da Force [EMAIL PROTECTED] writes: It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} NewDict = {} for x in Dict.keys(): try: NewDict[Dict[x]].append(x) except KeyError: NewDict[Dict[x]] = [x] Or, more up-to-date: NewDict = {} for key, val in Dict.iteritems(): NewDict.setdefault(val, []).append(key) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
How does setdefault work exactly? I am looking in the docs and can't figure it out... Ric Ric Da Force [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Thank you guys! (Reinhold, Mark and Markus) I must confess that I am absolutely awe struck at the power of this language! There is no way in the world that I would have envisaged such simple and elegant solutions!!! Reinhold, is your solution specific to 2.4? Kind Regards, Ric Reinhold Birkenfeld [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Mark Jackson wrote: Ric Da Force [EMAIL PROTECTED] writes: It is hard to explain but this is what I mean: Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is not'} I want this to return a new dict with string keys and lists containing the previous keys for repeated values. NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']} NewDict = {} for x in Dict.keys(): try: NewDict[Dict[x]].append(x) except KeyError: NewDict[Dict[x]] = [x] Or, more up-to-date: NewDict = {} for key, val in Dict.iteritems(): NewDict.setdefault(val, []).append(key) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Dictionary Question from newbie
Ric Da Force wrote: How does setdefault work exactly? I am looking in the docs and can't figure it out... If the key (the first argument) already exists in the dictionary, the corresponding value is returned. If the key does not exist in the dictionary, it is stored in the dictionary and bound to the second argument, and then that second argument is returned as the value. (I always have to ignore the name to think about how it works, or it gets in the way of my understanding it. The name makes fairly little sense to me.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
A simple way to get individual values for the distribution is: d = {} for i in range( 0, 1000): j = random.randrange( 0, 100) if d.has_key(j): d[j] += 1 else: d[j] = 1 keys = d.keys() keys.sort() for key in keys: print key, :, * * d[key] -- http://mail.python.org/mailman/listinfo/python-list
Dictionary question.
Hi, I am semi new to Python. Here is my problem : I have a list of 100 random integers. I want to be able to construct a histogram out of the data. So I want to know how many 70's, 71's, etc. I can't figure out how to do this. A dictionary is supposedly can do key value pairs right? I want to be able to see if say 75 is in the data structure, and what its value is, then increment its value as I go through the list finding items. I am sure there is a way to do this. Is a dictionary what I should be using? Thanks for any help. Hope this makes sense, its getting very late here. Regards all. Ed -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
On 21 Apr 2005 02:47:42 -0700, hawkesed [EMAIL PROTECTED] wrote: I am semi new to Python. Here is my problem : I have a list of 100 random integers. I want to be able to construct a histogram out of the data. So I want to know how many 70's, 71's, etc. I can't figure out how to do this. A dictionary is supposedly can do key value pairs right? I want to be able to see if say 75 is in the data structure, and what its value is, then increment its value as I go through the list finding items. I am sure there is a way to do this. Is a dictionary what I should be using? Thanks for any help. Hope this makes sense, its getting very late here. Sounds like homework, so I'll just say that yes, a dictionary would be ideal for what you are trying to do. -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
Simon Brunning wrote: On 21 Apr 2005 02:47:42 -0700, hawkesed [EMAIL PROTECTED] wrote: I am semi new to Python. Here is my problem : I have a list of 100 random integers. I want to be able to construct a histogram out of the data. So I want to know how many 70's, 71's, etc. I can't figure out how to do this. A dictionary is supposedly can do key value pairs right? I want to be able to see if say 75 is in the data structure, and what its value is, then increment its value as I go through the list finding items. I am sure there is a way to do this. Is a dictionary what I should be using? Thanks for any help. Hope this makes sense, its getting very late here. Sounds like homework, so I'll just say that yes, a dictionary would be ideal for what you are trying to do. And I will add that you have two different cases to cope with: the first time you come across a particular value you have to create a new element with a value of one. The second and subsequent times you have to add one to an existing element. regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
hawkesed [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I am semi new to Python. Here is my problem : I have a list of 100 random integers. I want to be able to construct a histogram out of the data. So I want to know how many 70's, 71's, etc. I can't figure out how to do this. A dictionary is supposedly can do key value pairs right? I want to be able to see if say 75 is in the data structure, and what its value is, then increment its value as I go through the list finding items. I am sure there is a way to do this. Is a dictionary what I should be using? Thanks for any help. Hope this makes sense, its getting very late here. The goal of making a histogram implies that there more numbers in rlist than possible values in range[min(rlist), max(rlist)+1]. I would use a list. freq = [0]*(rmax-rmin+1) for i in randomlist: freq[rmin+i] += 1 You can then further combine bins as needed for a histogram. If your distribution is sparse instead of compact, a dict would be better, but 'random integer [in a range]' usually implies compactness. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
Here is an example of the input list: [101, 66, 75, 107, 108, 101, 106, 98, 111, 88, 119, 93, 115, 95, 114, 95, 118, 109, 85, 75, 88, 97, 53, 78, 98, 91, 115, 77, 107, 153, 108, 101] Here is the code I am working on now: for num in alist: ... if adict.has_key(num): ... x = adict.get(num) ... x = x + 1 // update the value here else // add the new value here. Its these two commented out lines that I am working on. For the record, I am not in a python class. I am trying to learn python. For one thing I thought it looks like it would be a good tool to work with math and statistics stuff. Thanks for the help. Have a great day. Ed -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
Steve, thanks for the input. That is actually what I am trying to do, but I don't know the syntax for this in python. For example here is a list I want to work with as input: [101, 66, 75, 107, 108, 101, 106, 98, 111, 88, 119, 93, 115, 95, 114, 95, 118, 109, 85, 75, 88, 97, 53, 78, 98, 91, 115, 77, 107, 153, 108] Here is as far as I have gotten coding: for num in alist: ... if adict.has_key(num): ... x = adict.get(num) ... x = x + 1 # dont know how to update a value here else: // add key with value one here somehow. Thats where I am at now. For the record, I am not taking a class on python and using this forum to do my homework. I graduated in 1999 and am trying to get familiar with python and refresh my statistics skills. Python seems like it would be a good language to do math/stat work in, in a lightweight way. Thank for all the help and have a great day! Ed -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
Actually, I think I got it now. Here is what I did: for num in alist: ... if adict.has_key(num): ... x = adict.get(num) ... x = x + 1 ... adict.update({num:x}) ... else: ... adict.update({num:1}) ... adict {128: 2, 129: 2, 132: 1, 153: 1, 30: 1, 53: 1, 57: 1, 61: 1, 66: 2, 67: 1, 69: 2, 71: 1, 72: 1, 73: 2, 74: 1, 75: 2, 76: 2, 77: 2, 78: 2, 82: 1, 84: 1, 85: 4, 87: 2, 88: 3, 89: 1, 91: 1, 92: 1, 93: 2, 94: 2, 95: 3, 96: 1, 97: 3, 98: 2, 99: 1, 100: 6, 101: 4, 102: 2, 103: 1, 104: 1, 105: 1, 106: 2, 107: 2, 108: 2, 109: 2, 111: 3, 112: 1, 114: 3, 115: 3, 116: 3, 118: 1, 119: 2, 122: 2, 123: 1, 125: 1, 126: 1} Thanks all for the help and best regards! Ed -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
hawkesed said unto the world upon 2005-04-21 20:28: Actually, I think I got it now. Here is what I did: for num in alist: ... if adict.has_key(num): ... x = adict.get(num) ... x = x + 1 ... adict.update({num:x}) ... else: ... adict.update({num:1}) ... adict {128: 2, 129: 2, 132: 1, 153: 1, 30: 1, 53: 1, 57: 1, 61: 1, 66: 2, 67: 1, 69: 2, 71: 1, 72: 1, 73: 2, 74: 1, 75: 2, 76: 2, 77: 2, 78: 2, 82: 1, 84: 1, 85: 4, 87: 2, 88: 3, 89: 1, 91: 1, 92: 1, 93: 2, 94: 2, 95: 3, 96: 1, 97: 3, 98: 2, 99: 1, 100: 6, 101: 4, 102: 2, 103: 1, 104: 1, 105: 1, 106: 2, 107: 2, 108: 2, 109: 2, 111: 3, 112: 1, 114: 3, 115: 3, 116: 3, 118: 1, 119: 2, 122: 2, 123: 1, 125: 1, 126: 1} Thanks all for the help and best regards! Ed Hi Ed, I think there is a more Pythonic way. Here's something I used in a similar context: def get_frequency_dict(sequence): '''sequence of hashables - dictionary of frequency of members Given a sequence of items, each of which is hashable (i.e. can serve as a key in a dictionary), the function returns a dictionary, using the items as keys, and the number of their occurrences as values. Usage: get_frequency_dict([1,2,2,3,3,3,4,4,4,4]) {1: 1, 2: 2, 3: 3, 4: 4} get_frequency_dict([[], will fail as list aren't hashable]) ... TypeError: list objects are unhashable ''' frequency_dict = {} for element in sequence: frequency_dict[element] = frequency_dict.setdefault( element, 0) + 1 return frequency_dict HTH, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary question.
hawkesed wrote: Actually, I think I got it now. Here is what I did: for num in alist: ... if adict.has_key(num): ... x = adict.get(num) ... x = x + 1 ... adict.update({num:x}) A simpler way to do this last line is adict[num] = x ... else: ... adict.update({num:1}) and adict[num] = 1 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: probably weird or stupid newbie dictionary question
Diez B. Roggisch [EMAIL PROTECTED] wrote: But what happens in case of a hash code clash? Then a list of (key, values) is stored, and for a passed key, each key in that list is additionally compared for being equal to the passed one. So another requirement of hashable objecst is the comparability. In java, this is done using the equals method. So in the end, the actual mapping of key, value looks like this: hash(key) - [(key, value), ] Thats called hashing with chaining. See Knuth: Sorting and Searching if you want to know more! -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
probably weird or stupid newbie dictionary question
I've read in several places that a Python dictionary is analagous to some other languages' hash table (Perl's, for instance). But FMU a dictionary's keys are *themselves* hashed so that a hash table exists that maps hashed key values to keys in the dictionary. ISTM, then, that the analogy is at least somewhat faulty...except for the fact that a dictionary's keys could themselves be hashed redundantly...i.e., the values to be used as keys could be hashed, inserted into the dictionary (and mapped to their values, of course), and they would then be hashed (again) behind the scenes...IOW, ISTM that a dictionary is correctly understood generally as a mapping (as documentation indicates) and *could* be understood as a special case hash table itself...Is that accurate? h -- http://mail.python.org/mailman/listinfo/python-list
Re: probably weird or stupid newbie dictionary question
hawkmoon269 schrieb: some other languages' hash table (Perl's, for instance). But FMU a dictionary's keys are *themselves* hashed so that a hash table exists that maps hashed key values to keys in the dictionary. I guess you're mixing up the terms hashing and storing in a hash-table. When we hash a dictionary key a = hash(key) then we retrieve a value that is used to refer to the value that we want to store. Ok? :) 1 mydict = {} 2 mydict['mykey'] = 'somevalue' 3 mydict['mykey'] 'somevalue' What happened, was: 1) mydict becomes a dictionary 2a) mydict hashed the key 'mykey' and got an integer value. Strings know how to calculate a hash value for themselves, that value is retrieved via a call to hash('mykey') 2b) mydict then stored the value 'myvalue' at a location that the hashed key refers to (don't care how that is done) 3) mydict hashes the key 'mykey' and retrieves an integer. It looks at the location that that int refers to and finds the value 'somevalue' that was previously stored there. It returns that value. A bit clearer now? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: probably weird or stupid newbie dictionary question
That makes sense. Thanks. :-) h -- http://mail.python.org/mailman/listinfo/python-list
Re: probably weird or stupid newbie dictionary question
Very. Thanks much. :-) h -- http://mail.python.org/mailman/listinfo/python-list