Re: [Tutor] Dictionary viceversa
On 30/07/18 19:11, Zachary Ware wrote: > On Mon, Jul 30, 2018 at 1:08 PM Alan Gauld via Tutor wrote: >> There are lots of options including those suggested elsewhere. >> Another involves using get() which makes your function >> look like: >> >> def viceversa(d): >> new_d = dict() >> for k in d: >> for e in d[k]: >> new_d[e] = new_d.get(e,[]).append(k) > > Note that this will set each entry to `None` as returned by `list.append`. Oops, yes. You need an intermediate variable: for e in d[k]: data = new_d.get(e,[]) data.append(k) new_d[e] = data Or use addition: for e in d[k]: new_d[e] = new_d.get(e,[]) + [k] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary viceversa
On Mon, Jul 30, 2018 at 1:08 PM Alan Gauld via Tutor wrote: > There are lots of options including those suggested elsewhere. > Another involves using get() which makes your function > look like: > > def viceversa(d): > new_d = dict() > for k in d: > for e in d[k]: > new_d[e] = new_d.get(e,[]).append(k) Note that this will set each entry to `None` as returned by `list.append`. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary viceversa
On 30/07/18 13:40, Valerio Pachera wrote: > users = {'user1':['office-a', 'office-b'], > 'user2':['office-b'], > 'user3':['office-a','office-c']} > > It's a list of users. > For each user there's a list of room it can access to. > > I wish to get the same info but "sorted" by room. Remember that dicts are not sorted. You can create a dictionary keyed by room but not sorted by room. (You can however get a list of sorted keys but that's different, and you can use a collections.OrderedDict) > And i generalized it in a function like this: > > def viceversa(d): > new_d = dict() > for k in d: > for e in d[k]: > if e in new_d: > new_d[e].append(k) > else: > new_d[e] = [] > new_d[e].append(k) > return(new_d) > > My question is: is there a better way to that? There are lots of options including those suggested elsewhere. Another involves using get() which makes your function look like: def viceversa(d): new_d = dict() for k in d: for e in d[k]: new_d[e] = new_d.get(e,[]).append(k) return(new_d) > Maybe by list comprehension? I can't think of a reasonable way of doing that but a generator may work. Another option would be to build a set of the original rooms then iterate over the data, collecting the keys which have those rooms. But that would be pretty inefficient... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary viceversa
Zachary Ware wrote: > On Mon, Jul 30, 2018 at 12:20 PM Valerio Pachera wrote: >> I was looking to substiture the cicle for e in new_d like this: >> [ new_d[e].append(k) if e in new_d else new_d[e].append(k) for e in >> [ d[k] ] >> but it can't work because 'new_d[e] = []' is missing. > > Have a look at `dict.setdefault` and play around with it; I think it > will help you do what you want. Either that, or use a defaultdict: >>> import collections >>> room_access = collections.defaultdict(list) >>> for user, rooms in users.items(): ... for room in rooms: ... room_access[room].append(user) ... >>> room_access defaultdict(, {'office-c': ['user3'], 'office-b': ['user2', 'user1'], 'office-a': ['user3', 'user1']}) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary viceversa
On Mon, Jul 30, 2018 at 12:20 PM Valerio Pachera wrote: > I was looking to substiture the cicle for e in new_d like this: > [ new_d[e].append(k) if e in new_d else new_d[e].append(k) for e in d[k] ] > but it can't work because 'new_d[e] = []' is missing. Have a look at `dict.setdefault` and play around with it; I think it will help you do what you want. -- Zach ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
On Mon, May 2, 2016 at 5:28 PM Jason N. via Tutorwrote: > Hello, > Wanted to ask if its possible to have a dictionary that can be looked up > by either values? > For example, > mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple" to > come. But if the user enter "Apple" I want "A" to respond. > Please let me know the best way to handle this type cause instead of just > created duplicate entries to cover all possibilities. Thank you. > A dictionary enforces that the keys are unique, but many keys may have the same value. Do you want to enforce that values are unique? If not, does it matter which key is returned if many keys have the same value? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
On Mon, May 2, 2016 at 8:58 PM Jason N. via Tutorwrote: > What is the best way to make dictionary requests case in-sensitive? For > example, "Apple and "apple" should bring back the same dictionary > response. Thank you. > Take a look at how the requests library solves the problem with a "CaseInsensitiveDict" ( https://github.com/kennethreitz/requests/blob/master/requests/structures.py) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
Hello, Using iteritems would be much easier approach Something like this mydic = {"A": "Apple", "B": "Banana"} for key, value in mydic.iteritems(): if value == "Apple": print key Thanks & BR, Bharath Shetty On Tuesday, 3 May 2016 2:57 AM, Jason N. via Tutorwrote: Thank you all for your responses. A quick follow up, what is the best way to make dictionary requests case in-sensitive? For example, "Apple and "apple" should bring back the same dictionary response. Thank you. On Monday, May 2, 2016 6:57 PM, Bob Gailer wrote: On May 2, 2016 5:27 PM, "Jason N. via Tutor" wrote: > > Hello, > Wanted to ask if its possible to have a dictionary that can be looked up by > either values? > For example, > mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple" to > come. But if the user enter "Apple" I want "A" to respond. I think this would depend on how big the data set is and how often you want to look things up. Two other Solutions: Create a class which internally manages two dictionaries. If things are really big create a database using for example sqlite. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
On 03May2016 00:56, Jason N.wrote: Thank you all for your responses. A quick follow up, what is the best way to make dictionary requests case in-sensitive? For example, "Apple and "apple" should bring back the same dictionary response. Thank you. There are a few ways depending what your more fine grained objectives are. But they all tend to revolve around "normalising" the keys, which is a common practice for many things where multiple values are considered the same: in your case upper and lower case. So the easy thing is to always convert to lower case (or upper case, but lower case is less SHOUTY). Eg: def save(d, key, value): d[key.lower()] = value so the normalising function here is d.lower. Usually you'd be making yourself a mapping class of some kind: an object which behaves like a dictionay: https://docs.python.org/3/glossary.html#term-mapping And internally it would usually have a dictionary for storage. Completely untested example code: class CaseInsensitiveMapping: def __init__(self): self._d = {} def __getitem__(self, key): return self._d[key.lower()] def __setitem__(self, key, value): self._d[key.lower()] = value and so forth for the other special ("dunder" in Pythonspeak) methods used to implement a mapping: https://docs.python.org/3/reference/datamodel.html#emulating-container-types From the outside: cimap = CaseInsensitiveMapping() cimap['X']=1 print(cimap['x']) should print 1. Now having sketched a trivial example like this, you might need to be more elaborate depending on youruse case. For example, some mappings like this one preserve the case used to insert the original key. So while ['X'] and ['x'] would both find the value 1, they .keys() method with recite 'X' because that was the specific string used to put the 1 into the mapping. That would make the internal implementation more complicated. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
If only I understand what you mean. You can just make all the values in the dictionary lower, upper or capitalized. Then if you want take an input or whatever you want to do with it just use .lower() or .upper() or .capitalized() to convert it to what is in the dictionary. Maybe someone has a better way to do it :) Sent from my iPhone > On May 2, 2016, at 7:59 PM, Jason N. via Tutorwrote: > > Thank you all for your responses. > A quick follow up, what is the best way to make dictionary requests case > in-sensitive? For example, "Apple and "apple" should bring back the same > dictionary response. Thank you. > >On Monday, May 2, 2016 6:57 PM, Bob Gailer wrote: > > > > >> On May 2, 2016 5:27 PM, "Jason N. via Tutor" wrote: >> >> Hello, >> Wanted to ask if its possible to have a dictionary that can be looked up by >> either values? >> For example, mydic = {"A: "Apple", "B": "Banana"} >> When user inputs "A" I want "Apple" to come. But if the user enter "Apple" I >> want "A" to respond. > I think this would depend on how big the data set is and how often you want > to look things up. > Two other Solutions: > Create a class which internally manages two dictionaries. > If things are really big create a database using for example sqlite. > > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
Thank you all for your responses. A quick follow up, what is the best way to make dictionary requests case in-sensitive? For example, "Apple and "apple" should bring back the same dictionary response. Thank you. On Monday, May 2, 2016 6:57 PM, Bob Gailerwrote: On May 2, 2016 5:27 PM, "Jason N. via Tutor" wrote: > > Hello, > Wanted to ask if its possible to have a dictionary that can be looked up by > either values? > For example, > mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple" to > come. But if the user enter "Apple" I want "A" to respond. I think this would depend on how big the data set is and how often you want to look things up. Two other Solutions: Create a class which internally manages two dictionaries. If things are really big create a database using for example sqlite. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
On May 2, 2016 5:27 PM, "Jason N. via Tutor"wrote: > > Hello, > Wanted to ask if its possible to have a dictionary that can be looked up by either values? > For example, > mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple" to come. But if the user enter "Apple" I want "A" to respond. I think this would depend on how big the data set is and how often you want to look things up. Two other Solutions: Create a class which internally manages two dictionaries. If things are really big create a database using for example sqlite. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
On 02/05/16 22:55, isaac tetteh wrote: > > For some reason i cant find reply all . But try this > for key, value in mydic.items(): > If A==value: >Print key or as a function: def findKey(dct, val): for k,v in dct.items(): if v == val: return k mydic = {"A: "Apple", "B": "Banana"} print( findKey(mydic,'Apple') ) # -> 'A' The problem is that while keys are unique, values might not be, so what do you do if multiple keys share the same value? You could use a comprehension: def findKeys(dct,val): keys = [k for k,v in dct.items() if v == val] return keys But if you are only interested in one of them then it's down to you to figure out which! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
Sorry for the if statement the correct statement should be "if 'apple' ==value:" Sent from my iPhone > On May 2, 2016, at 4:58 PM, isaac tettehwrote: > > > For some reason i cant find reply all . But try this > for key, value in mydic.items(): > If A==value: > Print key > Nb: use iteritems() if using python2 > > Sent from my iPhone > >> On May 2, 2016, at 4:29 PM, Jason N. via Tutor wrote: >> >> Hello, >> Wanted to ask if its possible to have a dictionary that can be looked up by >> either values? >> For example, >> mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple" to >> come. But if the user enter "Apple" I want "A" to respond. >> Please let me know the best way to handle this type cause instead of just >> created duplicate entries to cover all possibilities. Thank you. >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
For some reason i cant find reply all . But try this for key, value in mydic.items(): If A==value: Print key Nb: use iteritems() if using python2 Sent from my iPhone > On May 2, 2016, at 4:29 PM, Jason N. via Tutorwrote: > > Hello, > Wanted to ask if its possible to have a dictionary that can be looked up by > either values? > For example, > mydic = {"A: "Apple", "B": "Banana"}When user inputs "A" I want "Apple" to > come. But if the user enter "Apple" I want "A" to respond. > Please let me know the best way to handle this type cause instead of just > created duplicate entries to cover all possibilities. Thank you. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary on data
jarod_v6--- via Tutor wrote: > Dear All! > I have this elements > > In [445]: pt = line.split("\t")[9] > > In [446]: pt > Out[446]: 'gene_id "ENSG0223972"; gene_version "5"; transcript_id > "ENST0456328"; transcript_version "2"; exon_number "1"; gene_name > "DDX11L1"; gene_source "havana"; gene_biotype > "transcribed_unprocessed_pseudogene"; transcript_name "DDX11L1-002"; > transcript_source "havana"; transcript_biotype "processed_transcript"; > exon_id "ENSE2234944"; exon_version "1"; tag "basic"; > transcript_support_level "1";\n' > > > and I want to create a dictionary like this > > gene_id = "ENSG0223972"; ... > > > I found on stack over flow this way to create a dictionary of dictionary > (http://stackoverflow.com/questions/8550912/python-dictionary-of-dictionaries) > # This is our sample data > data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", > "Malter", 2)] > > # dictionary we want for the result > dictionary = {} > > # loop that makes it work > for realName, falseName, position in data: > dictionary.setdefault(realName, {})[falseName] = position > > I want to create a dictionary using setdefault but I have difficult to > trasform pt as list of tuple. > > data = pt.split(";") > in () > 1 for i in data: > 2 l = i.split() > > 3 print l[0] > 4 > > IndexError: list index out of range > > In [457]: for i in data: > l = i.split() > print l >.: > ['gene_id', '"ENSG0223972"'] > ['gene_version', '"5"'] > ['transcript_id', '"ENST0456328"'] > ['transcript_version', '"2"'] > ['exon_number', '"1"'] > ['gene_name', '"DDX11L1"'] > ['gene_source', '"havana"'] > ['gene_biotype', '"transcribed_unprocessed_pseudogene"'] > ['transcript_name', '"DDX11L1-002"'] > ['transcript_source', '"havana"'] > ['transcript_biotype', '"processed_transcript"'] > ['exon_id', '"ENSE2234944"'] > ['exon_version', '"1"'] > ['tag', '"basic"'] > ['transcript_support_level', '"1"'] > [] > > > So how can do that more elegant way? > thanks so much!! I don't see why you would need dict.setdefault(), you have the necessary pieces together: data = pt.split(";") pairs = (item.split() for item in data) mydict = {item[0]: item[1].strip('"') for item in pairs if len(item) == 2} You can protect against whitespace in the quoted strings with item.split(None, 1) instead of item.split(). If ";" is allowed in the quoted strings you have to work a little harder. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 08/08/15 00:05, Ltc Hotspot wrote: Hi Alan, On line 15, I replaced: 'count[address] = count.get(address, 0) + 1' with 'line = Counter(address)'. line = Counter(address) will create a new Counter object with the address in it with a count value of 1. Every line in the file will create a new Counter, overwriting the previous one. At the end of the loop you will have exactly 1 Counter containing the last item in the loop and a count of 1. Instead create the Counter before the loop and then use the update() method to add the address to it. Recall we talked about reading the Counter documentation? It describes the update() method. One you have the Counter with all the addresses in you can get the max value and key directly without using a second loop and your maxkee and maxval variables. Again read the Counter documentation to see how. Finally remember the imports. You never show us those but the Counter will not work unless you import it. Question: What is the cause of the empty dict? You create it but never use it. You replaced the line where count got populated with your Counter call. So count never gets populated. Just because Counter sounds like count does not mean they are in any way connected. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 8/6/2015 5:30 PM, Ltc Hotspot wrote: I'm following the instructor's video exercise, available at https://www.youtube.com/watch?v=3cwXN5_3K6Q. As you're clearly interested in learning python, you may find working the tutorial beneficial as it steps you through the fundamentals of python in a time tested way. See https://docs.python.org/2/tutorial/ for python2 or https://docs.python.org/3/tutorial/ for python3. Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Alan, I want to find the max val , keys and values are defined on line 10: for kee, val in count.items(): Then, maxval determines the max value on line 11: if val maxval: right, view a copy of the revised code at http://tinyurl.com/nvzdw8k Question1: are these assumptions true, above? Question2: dict maps strings into keys and values? Hal On Thu, Aug 6, 2015 at 11:35 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 07/08/15 01:15, Ltc Hotspot wrote: Question1: How type of argument should I use for dict, i.e.,user argument or list argument. Read captured traceback: TypeError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_26.py in module() 1 fname = raw_input(Enter file name: ) 2 handle = open (fname, 'r') 3 count = dict.keys() 4 for line in handle: 5 if line.startswith(From: ): You appear to be making random changes to your code for no good reason. I will not make any further suggestions until you start to explain your thinking. What do you think the line count = dict.keys() will do? Why do you want to do that? How will it help you solve your problem? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Mark, I'm following the instructor's video exercise, available at https://www.youtube.com/watch?v=3cwXN5_3K6Q. View attached screen shot file, image file shows a copy of the counter: cou[wrd] =cou.get(wrd,0) +1 Please, explain the differences in counter methods? Hal On Thu, Aug 6, 2015 at 4:53 PM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 06/08/2015 20:05, Ltc Hotspot wrote: On my breath and soul, I did: Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError https://docs.python.org/3/library/exceptions.html#KeyError: That's nice to know. What do the rest of the methods on the class do? Please don't top post here, it makes following long threads difficult. What did you not understand about the above? You obviously haven't bothered to read the link I gave you about the Counter class so I give up. If you'd read the entire write up why are you still wasting time with a loop to find a maximum that simply doesn't work, when there is likely a solution in the Counter class right in front of your eyes? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Question1: How type of argument should I use for dict, i.e.,user argument or list argument. Read captured traceback: TypeError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_26.py in module() 1 fname = raw_input(Enter file name: ) 2 handle = open (fname, 'r') 3 count = dict.keys() 4 for line in handle: 5 if line.startswith(From: ): TypeError: descriptor 'keys' of 'dict' object needs an argument In [99]: Question2: Are all the loop failures resolved in the revised code? Revised code is available at https://gist.github.com/ltc-hotspot/00fa77ca9b40c0a77170 Regards, Hal On Thu, Aug 6, 2015 at 4:20 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 07/08/15 00:11, Ltc Hotspot wrote: Questions(1):Why does print line, prints blank space; and, (2) print address prints a single email address: See my previous emails. You are not storing your addresses so address only holds the last address in the file. line is at the end of the file so is empty., In [72]: print count {'gopal.ramasammyc...@gmail.com mailto:gopal.ramasammyc...@gmail.com': 1, 'lo...@media.berkeley.edu mailto:lo...@media.berkeley.edu': 3, 'cwen@iupui. edu': 5, 'antra...@caret.cam.ac.uk mailto:antra...@caret.cam.ac.uk': 1, 'rjl...@iupui.edu mailto:rjl...@iupui.edu': 2, 'gsil...@umich.ed u': 3, 'david.horw...@uct.ac.za mailto:david.horw...@uct.ac.za': 4, ' wagne...@iupui.edu mailto:wagne...@iupui.edu': 1, 'zq...@umich.edu mailto:zq...@umich.edu': 4, 'stephen.marqu...@uct.ac.za mailto:stephen.marqu...@uct.ac.za': 2, 'r...@media.berkeley.edu mailto:r...@media.berkeley.edu': 1} Question(3): why did the elements print count('keys') and print count('items') fail? Because, as shown above, count is a dictionary. So items and keys are methods not strings to be passed to a non-existent count() function. So you need, for example: print count.keys() Traceback (most recent call last) ipython-input-76-35c8707b256e in module() 1 print count('items') TypeError: 'dict' object is not callable Which is what the error is also telling you. You cannot call - ie use () - with a dictionary like count. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 07/08/15 01:15, Ltc Hotspot wrote: Question1: How type of argument should I use for dict, i.e.,user argument or list argument. Read captured traceback: TypeError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_26.py in module() 1 fname = raw_input(Enter file name: ) 2 handle = open (fname, 'r') 3 count = dict.keys() 4 for line in handle: 5 if line.startswith(From: ): You appear to be making random changes to your code for no good reason. I will not make any further suggestions until you start to explain your thinking. What do you think the line count = dict.keys() will do? Why do you want to do that? How will it help you solve your problem? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 07/08/2015 01:30, Ltc Hotspot wrote: Mark, I'm following the instructor's video exercise, available at https://www.youtube.com/watch?v=3cwXN5_3K6Q. View attached screen shot file, image file shows a copy of the counter: cou[wrd] =cou.get(wrd,0) +1 Please, explain the differences in counter methods? top posted, again, *plonk* -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Hi Mark, Why is Counter not defined on line #15: line = Counter(address),i.e., NameError: name 'Counter' is not defined? Share a chat session at http://tinyurl.com/oull2fw View line entry at http://tinyurl.com/oggzn97 Hal On Fri, Aug 7, 2015 at 12:14 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 07/08/2015 01:30, Ltc Hotspot wrote: Mark, I'm following the instructor's video exercise, available at https://www.youtube.com/watch?v=3cwXN5_3K6Q. View attached screen shot file, image file shows a copy of the counter: cou[wrd] =cou.get(wrd,0) +1 Please, explain the differences in counter methods? top posted, again, *plonk* -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 07/08/15 19:18, Ltc Hotspot wrote: I want to find the max val , keys and values are defined on line 10: for kee, val in count.items(): Yes we know that, but you are not answering the questions we pose. Instead you seem to post random changes to your code and ask new questions which makes it hard to know whether you understand what is going on and to guide you to a solution. Then, maxval determines the max value on line 11: if val maxval: right, view a copy of the revised code at http://tinyurl.com/nvzdw8k OK, You have only posted partial code because you don't have the part where you read the filename etc. But assuming it has not changed then the new code looks correct - almost. Your assignment said NOT to use the lines starting From: (with colon :) But your code tests for startswith('From: ') so you are doing what you were told not to do. If you remove the colon from the end of From (but keep the space) it should be correct. Question1: are these assumptions true, above? Yes, pretty much correct. Question2: dict maps strings into keys and values? Not quite. A dictionary has a key and a corresponding value. The key can be ANY immutable (unchangeable) object - string, integer, tuple, etc. The value can be any Python object. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Mark, Visit the following URL link to view a captured copy of the latest code revision, available at http://tinyurl.com/nvzdw8k Regards, Hal On Thu, Aug 6, 2015 at 10:17 AM, Ltc Hotspot ltc.hots...@gmail.com wrote: On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 06/08/2015 05:22, Ltc Hotspot wrote: Please don't top post here, it makes following long threads difficult. Mark, Replace count[address]= count.get(address,0) +1 with c = Counter(['address'])? Try it at the interactive prompt and see what happens. How do I define counter,view trace back: NameError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\new.txt in module() 1 fname = raw_input(Enter file name: ) 2 handle = open (fname, 'r') 3 c = Counter(['address']) 4 5 NameError: name 'Counter' is not defined View revised code here: fname = raw_input(Enter file name: ) handle = open (fname, 'r') c = Counter(['address']) count = dict () maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 print maxkee and maxval In [20]: Hal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Hi Alan, I moved counter outside the loop and below dict, maxval = None maxkee = None are both positioned outside the loop. URL link to the revisions are available at http://tinyurl.com/nvzdw8k Question: How do I define Counter Revised code reads: fname = raw_input(Enter file name: ) handle = open (fname, 'r') counter = dict () c = Counter(['address']) maxval = None maxkee = None for line in handle: if line.startswith(From: ): address = line.split()[1] for maxkee, val in c.items(): maxval = val maxkee = kee print maxkee and maxval Traceback message reads: NameError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_16.py in module() 3 4 counter = dict () 5 c = Counter(['address']) 6 7 maxval = None NameError: name 'Counter' is not defined Regards, Hal On Thu, Aug 6, 2015 at 2:47 AM, Alan Gauld alan.ga...@btinternet.com wrote: On 06/08/15 03:27, Ltc Hotspot wrote: The output as reported by the latest code revision: c...@iupui.edu mailto:c...@iupui.edu 1← Mismatch Looks like python continues to print the wrong data set: Python will print what you ask it to. Don't blame the tool! :-) for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee print address, val Look at the loops. In the second loop you are no longer setting the values to those of the max item but are setting them every time. So at the end of the loop val holds the val of the last item (and so does maxval so even if you used that it would be the same result). Similarly with the code for address. You are setting that for each 'From ' line in your file so at the end of the loop address is the last address in the file. Now, dictionaries do not store data in the order that you insert it, so there is no guarantee that the last item in the dictionary loop is the same as the last address you read. You need to reinstate the test for max val in the second loop and then print the kee that corresponds with that (maxkee) as the address. ie. print maxkee and maxval. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/15 19:30, Ltc Hotspot wrote: I moved counter outside the loop and below dict, maxval = None maxkee = None are both positioned outside the loop. You moved counter but it is still a dict() and you don't use it anywhere. URL link to the revisions are available at http://tinyurl.com/nvzdw8k Question: How do I define Counter Counter is defined for you in the collections module. So to use it you need to import collections and access it as collections.Counter. But did you read how to use it? It is a lot more than just a dictionary, it has many extra methods, some of which almost solve your problem for you. (Whether your teacher will approve of using Counter is another issue!) Revised code reads: fname = raw_input(Enter file name: ) handle = open (fname, 'r') counter = dict () c = Counter(['address']) You only need to pass a list if you are adding multiple things. But by the same token you can add a list of items, such as email addresses. So if you had such a list you could create a Counter() to hold them and count them for you. And return the one with the highest value. Sound familiar? Please (re)read the Counter documentation. Then play with one in the prompt. Don't expect us to just provide you with code, learn how it works for yourself. Experiment. The prompt is your friend. You will learn more from that in 15 minutes than in a bunch of emails showing other peoples code. Alternatively forget about Counter and just go back to your dict(). You have written all the code you need already, you just need to assemble it in the correct order. maxval = None maxkee = None for line in handle: if line.startswith(From: ): address = line.split()[1] You are not storing the addresses anywhere. for maxkee, val in c.items(): maxval = val maxkee = kee You are still not testing if its the maximum, you just keep overwriting the variables for each element. print maxkee and maxval You still have an 'and' in there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/15 03:27, Ltc Hotspot wrote: The output as reported by the latest code revision: c...@iupui.edu mailto:c...@iupui.edu 1← Mismatch Looks like python continues to print the wrong data set: Python will print what you ask it to. Don't blame the tool! :-) for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee print address, val Look at the loops. In the second loop you are no longer setting the values to those of the max item but are setting them every time. So at the end of the loop val holds the val of the last item (and so does maxval so even if you used that it would be the same result). Similarly with the code for address. You are setting that for each 'From ' line in your file so at the end of the loop address is the last address in the file. Now, dictionaries do not store data in the order that you insert it, so there is no guarantee that the last item in the dictionary loop is the same as the last address you read. You need to reinstate the test for max val in the second loop and then print the kee that corresponds with that (maxkee) as the address. ie. print maxkee and maxval. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Mark, Replace count[address]= count.get(address,0) +1 with c = Counter(['address'])? Regards, Hal On Wed, Aug 5, 2015 at 9:03 PM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 05/08/2015 23:58, Ltc Hotspot wrote: Hi Mark, Address identifies the email address with the maximum number of sends: c...@iupui.edu. Secondly, we are missing a count on the number of messages sent by c...@iupui.edu, i.e., 5. Thirdly, maxval 'none' is not defined on line # 24 Questions: How do we define the value of none for the key maxval and retrieve a number count on the number of messages sent by c...@iupui.edu. NameError: Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_5.py in module() 22 ## find the greatest number of mail messages. 23 --- 24 maxval = none 25 maxkee = none 26 for kee, val in count.items(): NameError: name 'none' is not defined In [52]: print address c...@iupui.edu Revised data: ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. fname = raw_input(Enter file name: ) handle = open (fname, 'r') for line in handle: if line.startswith(From: ): address = line.split()[1] ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in address: count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee You can greatly simplify all of the above code if you use a Counter from the collections module https://docs.python.org/3/library/collections.html#collections.Counter -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On my breath and soul, I did: Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError https://docs.python.org/3/library/exceptions.html#KeyError: c = Counter(['eggs', 'ham']) On Thu, Aug 6, 2015 at 11:59 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 06/08/2015 18:17, Ltc Hotspot wrote: On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 06/08/2015 05:22, Ltc Hotspot wrote: Please don't top post here, it makes following long threads difficult. Mark, Replace count[address]= count.get(address,0) +1 with c = Counter(['address'])? Try it at the interactive prompt and see what happens. How do I define counter,view trace back: NameError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\new.txt in module() 1 fname = raw_input(Enter file name: ) 2 handle = open (fname, 'r') 3 c = Counter(['address']) 4 5 NameError: name 'Counter' is not defined View revised code here: fname = raw_input(Enter file name: ) handle = open (fname, 'r') c = Counter(['address']) count = dict () maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 print maxkee and maxval You obviously haven't bothered to read the link I gave you about the Counter class so I give up. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 07/08/15 00:11, Ltc Hotspot wrote: Questions(1):Why does print line, prints blank space; and, (2) print address prints a single email address: See my previous emails. You are not storing your addresses so address only holds the last address in the file. line is at the end of the file so is empty., In [72]: print count {'gopal.ramasammyc...@gmail.com mailto:gopal.ramasammyc...@gmail.com': 1, 'lo...@media.berkeley.edu mailto:lo...@media.berkeley.edu': 3, 'cwen@iupui. edu': 5, 'antra...@caret.cam.ac.uk mailto:antra...@caret.cam.ac.uk': 1, 'rjl...@iupui.edu mailto:rjl...@iupui.edu': 2, 'gsil...@umich.ed u': 3, 'david.horw...@uct.ac.za mailto:david.horw...@uct.ac.za': 4, 'wagne...@iupui.edu mailto:wagne...@iupui.edu': 1, 'zq...@umich.edu mailto:zq...@umich.edu': 4, 'stephen.marqu...@uct.ac.za mailto:stephen.marqu...@uct.ac.za': 2, 'r...@media.berkeley.edu mailto:r...@media.berkeley.edu': 1} Question(3): why did the elements print count('keys') and print count('items') fail? Because, as shown above, count is a dictionary. So items and keys are methods not strings to be passed to a non-existent count() function. So you need, for example: print count.keys() Traceback (most recent call last) ipython-input-76-35c8707b256e in module() 1 print count('items') TypeError: 'dict' object is not callable Which is what the error is also telling you. You cannot call - ie use () - with a dictionary like count. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/2015 20:05, Ltc Hotspot wrote: On my breath and soul, I did: Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError https://docs.python.org/3/library/exceptions.html#KeyError: That's nice to know. What do the rest of the methods on the class do? Please don't top post here, it makes following long threads difficult. What did you not understand about the above? You obviously haven't bothered to read the link I gave you about the Counter class so I give up. If you'd read the entire write up why are you still wasting time with a loop to find a maximum that simply doesn't work, when there is likely a solution in the Counter class right in front of your eyes? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On Thu, Aug 6, 2015 at 3:00 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 06/08/15 19:30, Ltc Hotspot wrote: I moved counter outside the loop and below dict, maxval = None maxkee = None are both positioned outside the loop. You moved counter but it is still a dict() and you don't use it anywhere. URL link to the revisions are available at http://tinyurl.com/nvzdw8k Question: How do I define Counter Counter is defined for you in the collections module. So to use it you need to import collections and access it as collections.Counter. But did you read how to use it? It is a lot more than just a dictionary, it has many extra methods, some of which almost solve your problem for you. (Whether your teacher will approve of using Counter is another issue!) Revised code reads: fname = raw_input(Enter file name: ) handle = open (fname, 'r') counter = dict () c = Counter(['address']) You only need to pass a list if you are adding multiple things. But by the same token you can add a list of items, such as email addresses. So if you had such a list you could create a Counter() to hold them and count them for you. And return the one with the highest value. Sound familiar? Please (re)read the Counter documentation. Then play with one in the prompt. Don't expect us to just provide you with code, learn how it works for yourself. Experiment. The prompt is your friend. You will learn more from that in 15 minutes than in a bunch of emails showing other peoples code. Alternatively forget about Counter and just go back to your dict(). You have written all the code you need already, you just need to assemble it in the correct order. maxval = None maxkee = None for line in handle: if line.startswith(From: ): address = line.split()[1] You are not storing the addresses anywhere. for maxkee, val in c.items(): maxval = val maxkee = kee You are still not testing if its the maximum, you just keep overwriting the variables for each element. print maxkee and maxval You still have an 'and' in there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Hi Alan, Questions(1):Why does print line, prints blank space; and, (2) print address prints a single email address: View print results as follows: In [70]: %run assignment_9_4_24.py Enter file name: mbox-short.txt r...@media.berkeley.edu 1 In [71]: print handle open file 'mbox-short.txt', mode 'r' at 0x035576F0 In [72]: print count {'gopal.ramasammyc...@gmail.com': 1, 'lo...@media.berkeley.edu': 3, 'cwen@iupui. edu': 5, 'antra...@caret.cam.ac.uk': 1, 'rjl...@iupui.edu': 2, 'gsil...@umich.ed u': 3, 'david.horw...@uct.ac.za': 4, 'wagne...@iupui.edu': 1, ' zq...@umich.edu': 4, 'stephen.marqu...@uct.ac.za': 2, 'r...@media.berkeley.edu': 1} In [73]: print line In [74]: print address c...@iupui.edu Question(3): why did the elements print count('keys') and print count('items') fail? View print commands as follows: In [75]: dir (count) Out[75]: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] In [76]: --- TypeError Traceback (most recent call last) ipython-input-76-35c8707b256e in module() 1 print count('items') TypeError: 'dict' object is not callable In [77]: print count('keys') --- TypeError Traceback (most recent call last) ipython-input-77-54ed4a05a3c7 in module() 1 print count('keys') TypeError: 'dict' object is not callable In [78]: Regards, Hal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/15 18:17, Ltc Hotspot wrote: View revised code here: fname = raw_input(Enter file name: ) handle = open (fname, 'r') c = Counter(['address']) count = dict () maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 print maxkee and maxval Let's hold up here a second. You do understand that Python executes your code from top to bottom, yes? So reading your code from the top you have a loop that sets maxval and maxkee before you even put anything into count. How do you think that would ever work? You have a lot of people spending time trying to help you here, but you do need to exercise a little bit of insight yourself. That code can never work and it has nothing to do with Pyhon it is your logic that is faulty. Try working through it with a pencil and paper. Write down what each variable contains at each stage of the program. (or just print it to see). You have been very close to a solution but you seem to be getting farther away rather than closer which suggests you are trying stuff without understanding why. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 06/08/2015 05:22, Ltc Hotspot wrote: Please don't top post here, it makes following long threads difficult. Mark, Replace count[address]= count.get(address,0) +1 with c = Counter(['address'])? Try it at the interactive prompt and see what happens. How do I define counter,view trace back: NameError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\new.txt in module() 1 fname = raw_input(Enter file name: ) 2 handle = open (fname, 'r') 3 c = Counter(['address']) 4 5 NameError: name 'Counter' is not defined View revised code here: fname = raw_input(Enter file name: ) handle = open (fname, 'r') c = Counter(['address']) count = dict () maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 print maxkee and maxval In [20]: Hal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/2015 18:17, Ltc Hotspot wrote: On Thu, Aug 6, 2015 at 8:28 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 06/08/2015 05:22, Ltc Hotspot wrote: Please don't top post here, it makes following long threads difficult. Mark, Replace count[address]= count.get(address,0) +1 with c = Counter(['address'])? Try it at the interactive prompt and see what happens. How do I define counter,view trace back: NameError Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\new.txt in module() 1 fname = raw_input(Enter file name: ) 2 handle = open (fname, 'r') 3 c = Counter(['address']) 4 5 NameError: name 'Counter' is not defined View revised code here: fname = raw_input(Enter file name: ) handle = open (fname, 'r') c = Counter(['address']) count = dict () maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 print maxkee and maxval You obviously haven't bothered to read the link I gave you about the Counter class so I give up. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/15 18:17, Ltc Hotspot wrote: Replace count[address]= count.get(address,0) +1 with c = Counter(['address'])? You didn't do what Mark suggested. Did you read the documentation about Counter? NameError Traceback (most recent call last) 2 handle = open (fname, 'r') 3 c = Counter(['address']) NameError: name 'Counter' is not defined So where do you define Counter? Do you import the module? Do you import Counter from the module? It's not shown in your code. View revised code here: fname = raw_input(Enter file name: ) handle = open (fname, 'r') c = Counter(['address']) count = dict () maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 print maxkee and maxval You have introduced an 'and' here which makes no sense. It will try to print the logical AND of the two values. That's not what you want. Please try to work through this manually and see how it works (or doesn't). There is no point in folks making suggestions for improvements until you understand how it should work yourself.b You have all the components needed to build the solution, now its up to you to fit them together such that they work. We can make suggestions but you need to solve the problem, we can't, and won't do it for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
The revised output reads: In [3]: %run assignment_9_4_9.py Enter file name: mbox-short.txt c...@iupui.edu 14 The desired output: c...@iupui.edu 5 Question: How do I trace the source of the count? Revised data code reads: fname = raw_input(Enter file name: ) handle = open (fname, 'r') count = dict () for line in handle: if line.startswith(From: ): address = line.split()[1] for wrd in address: count[wrd]= count.get(wrd,0) +1 maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee print address, val On Wed, Aug 5, 2015 at 4:11 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 05/08/15 15:15, Ltc Hotspot wrote: Raw data code reads: Being picky here but data and code are very different things (in most languages at least) and what you have below is definitely code not data. Meanwhile there are lots of issues in this code... fname = raw_input(Enter file name: ) handle = open (fname, 'r') text = handle.read() ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. addresses = set() for addr in [ text.split()[2]('From ') if fromline The above looks like its supposed to be a list comprehension embedded in a for loop. Putting too much code in one line is usually a bad idea especially before you have it working. Try separating out the formation of your list from the for loop. Once you get the comprehension working correctly then you can consider embedding it. As for the expression text.split()[2]('From ') Can you explain how you think that works? Try it at the prompt with text set to a sample line of data. -- What command did you type to get the triple chevrons ? -- My python interpreter: iPython (py.2.7) Try text = .. # whatever your data looks like text.split() text.split[2] text.split()[2]('From ') -- address data, review the latest revised code? The prompt is one of your most powerful tools while writing code, you should always have one ready to try stuff out. You can answer a lot of questions that way. ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in word: What is word? You don't define it anywhere? count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to -- imported address data, review revised code? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Hi Alan The output as reported by the latest code revision: c...@iupui.edu 1 ← Mismatch Looks like python continues to print the wrong data set: In [11]: print val 1 In [12]: print kee r...@media.berkeley.edu In [13]: print address c...@iupui.edu In order to complete the assignment, using data from the source file, python must print the email address of the maximum sender and the number of sends, i.e., c...@iupui.edu 5 I think the problem is in the placement of the counter? Question: What is the source of the dictionary keys and values: maxval = None maxkee = None Here is the latest revised code as follows: fname = raw_input(Enter file name: ) handle = open (fname, 'r') count = dict () for line in handle: if line.startswith(From: ): address = line.split()[1] count[address]= count.get(address,0) +1 maxval = None maxkee = None for kee, val in count.items(): maxval = val maxkee = kee print address, val Hal On Wed, Aug 5, 2015 at 6:21 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 05/08/15 23:58, Ltc Hotspot wrote: fname = raw_input(Enter file name: ) handle = open (fname, 'r') for line in handle: if line.startswith(From: ): address = line.split()[1] So far so good. ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() But here you create a brand new dictionary. Every time you go round the loop. And it wipes out the old one. You need to move that out of the loop. for wrd in address: address is a string. So wrd will be set to every character in the string. I don;t think that's what you want? count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none See my previous email. none should be None. Case matters in Python. for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee #items are printed print address Notice that address gets reset every time the loop reads a new line so this will only print the last address. But maybe that's what you wanted? -- Did I resolve the reset in the revised code? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/2015 05:22, Ltc Hotspot wrote: Please don't top post here, it makes following long threads difficult. Mark, Replace count[address]= count.get(address,0) +1 with c = Counter(['address'])? Try it at the interactive prompt and see what happens. Regards, Hal On Wed, Aug 5, 2015 at 9:03 PM, Mark Lawrence breamore...@yahoo.co.uk wrote: On 05/08/2015 23:58, Ltc Hotspot wrote: Hi Mark, Address identifies the email address with the maximum number of sends: c...@iupui.edu. Secondly, we are missing a count on the number of messages sent by c...@iupui.edu, i.e., 5. Thirdly, maxval 'none' is not defined on line # 24 Questions: How do we define the value of none for the key maxval and retrieve a number count on the number of messages sent by c...@iupui.edu. NameError: Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_5.py in module() 22 ## find the greatest number of mail messages. 23 --- 24 maxval = none 25 maxkee = none 26 for kee, val in count.items(): NameError: name 'none' is not defined In [52]: print address c...@iupui.edu Revised data: ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. fname = raw_input(Enter file name: ) handle = open (fname, 'r') for line in handle: if line.startswith(From: ): address = line.split()[1] ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in address: count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee You can greatly simplify all of the above code if you use a Counter from the collections module https://docs.python.org/3/library/collections.html#collections.Counter -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 05/08/2015 23:58, Ltc Hotspot wrote: Hi Mark, Address identifies the email address with the maximum number of sends: c...@iupui.edu. Secondly, we are missing a count on the number of messages sent by c...@iupui.edu, i.e., 5. Thirdly, maxval 'none' is not defined on line # 24 Questions: How do we define the value of none for the key maxval and retrieve a number count on the number of messages sent by c...@iupui.edu. NameError: Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_5.py in module() 22 ## find the greatest number of mail messages. 23 --- 24 maxval = none 25 maxkee = none 26 for kee, val in count.items(): NameError: name 'none' is not defined In [52]: print address c...@iupui.edu Revised data: ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. fname = raw_input(Enter file name: ) handle = open (fname, 'r') for line in handle: if line.startswith(From: ): address = line.split()[1] ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in address: count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee You can greatly simplify all of the above code if you use a Counter from the collections module https://docs.python.org/3/library/collections.html#collections.Counter -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 06/08/15 02:05, Ltc Hotspot wrote: The revised output reads: In [3]: %run assignment_9_4_9.py Enter file name: mbox-short.txt c...@iupui.edu mailto:c...@iupui.edu 14 The desired output: c...@iupui.edu mailto:c...@iupui.edu 5 See my other post. Count the number of letters in the address. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 05/08/15 23:58, Ltc Hotspot wrote: fname = raw_input(Enter file name: ) handle = open (fname, 'r') for line in handle: if line.startswith(From: ): address = line.split()[1] So far so good. ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() But here you create a brand new dictionary. Every time you go round the loop. And it wipes out the old one. You need to move that out of the loop. for wrd in address: address is a string. So wrd will be set to every character in the string. I don;t think that's what you want? count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none See my previous email. none should be None. Case matters in Python. for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee #items are printed print address Notice that address gets reset every time the loop reads a new line so this will only print the last address. But maybe that's what you wanted? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 05/08/15 15:15, Ltc Hotspot wrote: Raw data code reads: Being picky here but data and code are very different things (in most languages at least) and what you have below is definitely code not data. Meanwhile there are lots of issues in this code... fname = raw_input(Enter file name: ) handle = open (fname, 'r') text = handle.read() ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. addresses = set() for addr in [ text.split()[2]('From ') if fromline The above looks like its supposed to be a list comprehension embedded in a for loop. Putting too much code in one line is usually a bad idea especially before you have it working. Try separating out the formation of your list from the for loop. Once you get the comprehension working correctly then you can consider embedding it. As for the expression text.split()[2]('From ') Can you explain how you think that works? Try it at the prompt with text set to a sample line of data. Try text = .. # whatever your data looks like text.split() text.split[2] text.split()[2]('From ') The prompt is one of your most powerful tools while writing code, you should always have one ready to try stuff out. You can answer a lot of questions that way. ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in word: What is word? You don't define it anywhere? count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none none is not a value in Python. You need to spell it None for kee, val in count.items(): if maxval == none or maxval val: You don't really need the maxval == None check since None is considered less that all other numbers. maxval = val maxkee = kee print items What is items? It is not defined anywhere above. count.items is not the same as items. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 05/08/2015 15:15, Ltc Hotspot wrote: Hi everyone: I want to write a python program that reads through the data file of mbox-short.txt.Mbox-short.txt, i.e., download is available at http://www.py4inf.com/code/mbox-short.txt. Secondly, I want for python to figure out who sent the greatest number of mail messages. The output should read: c...@iupui.edu 5 However, there is a traceback message: In [40]: %run 9_4_4.py File C:\Users\vm\Desktop\apps\docs\Python\_9_4_4.py, line 19 count = dict() ^ SyntaxError: invalid syntax Raw data code reads: fname = raw_input(Enter file name: ) handle = open (fname, 'r') text = handle.read() ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. addresses = set() for addr in [ text.split()[2]('From ') if fromline ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in word: count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee print items Question: What is the cause of the dictionary line message? Learning to find these syntax errors is a skill you must learn for yourself. Very often the error occurs one or even more lines before the line on which the error is actually detected. So please go back from where the error is actually reported and see what you can find. Very strong hint, do not ask again until you've fixed at least two of the three errors, and there may be more :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
-Original Message- From: Tutor [mailto:tutor-bounces+crk=godblessthe...@python.org] On Behalf Of Mark Lawrence Sent: Wednesday, August 05, 2015 3:23 PM To: tutor@python.org Subject: Re: [Tutor] Dictionary Issue On 05/08/2015 15:15, Ltc Hotspot wrote: Hi everyone: I want to write a python program that reads through the data file of mbox-short.txt.Mbox-short.txt, i.e., download is available at http://www.py4inf.com/code/mbox-short.txt. Secondly, I want for python to figure out who sent the greatest number of mail messages. The output should read: c...@iupui.edu 5 However, there is a traceback message: In [40]: %run 9_4_4.py File C:\Users\vm\Desktop\apps\docs\Python\_9_4_4.py, line 19 count = dict() ^ SyntaxError: invalid syntax Raw data code reads: fname = raw_input(Enter file name: ) handle = open (fname, 'r') text = handle.read() ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. addresses = set() for addr in [ text.split()[2]('From ') if fromline ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in word: count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee print items Question: What is the cause of the dictionary line message? Learning to find these syntax errors is a skill you must learn for yourself. Very often the error occurs one or even more lines before the line on which the error is actually detected. So please go back from where the error is actually reported and see what you can find. Very strong hint, do not ask again until you've fixed at least two of the three errors, and there may be more :) It looks like the problem is with count=dict() Should be count=dict{} I may be wrong - U'm still a neophyte. crk ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
On 05/08/15 23:36, Clayton Kirkwood wrote: It looks like the problem is with count=dict() Should be count=dict{} I may be wrong - U'm still a neophyte. Yes, you're wrong! :-) the correct form is as shown count = dict() Its calling the type operation which looks like any other function and uses (). The more common way to create an empty dictionary is to use {} alone, like: count = {} Although count is probably a bad name choice since collections usually merit a plural name, eg counts But the OP's problems lie earlier in the code, as Mark has suggested. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
However, there is a traceback message: In [40]: %run 9_4_4.py File C:\Users\vm\Desktop\apps\docs\Python\_9_4_4.py, line 19 count = dict() ^ SyntaxError: invalid syntax Syntax error reporting is approximate: you might need to look a few lines earlier to get at the root problem. ... Reading... The for loop looks odd because there's a leading open bracket that looks out of place. for addr in [ text.split()[2]('From ') The following line uses an if conditional, but needs to offset the block with a : that appears to be missing. if fromline ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Issue
Hi Mark, Address identifies the email address with the maximum number of sends: c...@iupui.edu. Secondly, we are missing a count on the number of messages sent by c...@iupui.edu, i.e., 5. Thirdly, maxval 'none' is not defined on line # 24 Questions: How do we define the value of none for the key maxval and retrieve a number count on the number of messages sent by c...@iupui.edu. NameError: Traceback (most recent call last) C:\Users\vm\Desktop\apps\docs\Python\assignment_9_4_5.py in module() 22 ## find the greatest number of mail messages. 23 --- 24 maxval = none 25 maxkee = none 26 for kee, val in count.items(): NameError: name 'none' is not defined In [52]: print address c...@iupui.edu Revised data: ## The program looks for 'From ' lines and takes the second ## word of those lines as the person who sent the mail. fname = raw_input(Enter file name: ) handle = open (fname, 'r') for line in handle: if line.startswith(From: ): address = line.split()[1] ## The program creates a Python dictionary that maps ## the sender's mail address to a count of the number ## of times they appear in the file. count = dict() for wrd in address: count[wrd]= count.get(wrd,0) +1 ## After the dictionary is produced, the program reads ## through the dictionary using a maximum loop to ## find the greatest number of mail messages. maxval = none maxkee = none for kee, val in count.items(): if maxval == none or maxval val: maxval = val maxkee = kee #items are printed print address Regards, Hal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of lists
On Thu, Jun 4, 2015 at 2:30 AM, Peter Otten __pete...@web.de wrote: Chris Stinemetz wrote: Although I am certain it is not very efficient I was able to accomplish what I wanted with the following code I wrote: import os import pprint import csv from collections import defaultdict print_map = {'MOU':0, 'Call_Att':1, 'Device':2} header = ['IMEI','MOUs','Call_Att','Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' os.chdir(path) running_MOU = {} call_attempts = {} d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in running_MOU.keys(): For big dicts in Python 2 the test key in some_dict.keys() is indeed very inefficient as it builds a list of keys first and then performs a linear scan for the key. Much better: key in some_dict This test avoids building the list and can also use an efficient lookup algorithm that is independent of the size of the dict. running_MOU[IMEI] += Elapsed_Mins else: running_MOU[IMEI] = Elapsed_Mins if IMEI in call_attempts.keys(): call_attempts[IMEI] += 1 else: call_attempts[IMEI] = 1 # if key matches append mou else append 0. d[IMEI] = [running_MOU[IMEI]] d[IMEI].append([call_attempts[IMEI]]) d[IMEI].append([device]) print ,.join(header) for k,v in sorted(d.items()): print k, ,, d[k][print_map['MOU']],,, d[k][print_map['Call_Att']][0],,, d[k][print_map['Device']][0] print complete Here's an alternative that uses only one dict: import csv import os import sys header = ['IMEI', 'MOUs', 'Call_Att', 'Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' d = {} for fname in os.listdir(path): with open(os.path.join(path, fname)) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] elapsed_mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in d: record = d[IMEI] record[1] += elapsed_mins record[2] += 1 else: d[IMEI] = [IMEI, elapsed_mins, 1, device] writer = csv.writer(sys.stdout) writer.writerow(header) writer.writerows(sorted(d.itervalues())) print complete Peter - Thank you for showing me how to do this with one dictionary and a more efficient method to lookup dictionary keys. I originally attempted to accomplish this by using one dictionary but could not find a good example that is why I used the defaultdict module. Your approach sped the parsing time up from about 3 minutes to about 15 seconds! Very cool. Thanks, Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of lists
Chris Stinemetz wrote: Although I am certain it is not very efficient I was able to accomplish what I wanted with the following code I wrote: import os import pprint import csv from collections import defaultdict print_map = {'MOU':0, 'Call_Att':1, 'Device':2} header = ['IMEI','MOUs','Call_Att','Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' os.chdir(path) running_MOU = {} call_attempts = {} d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in running_MOU.keys(): For big dicts in Python 2 the test key in some_dict.keys() is indeed very inefficient as it builds a list of keys first and then performs a linear scan for the key. Much better: key in some_dict This test avoids building the list and can also use an efficient lookup algorithm that is independent of the size of the dict. running_MOU[IMEI] += Elapsed_Mins else: running_MOU[IMEI] = Elapsed_Mins if IMEI in call_attempts.keys(): call_attempts[IMEI] += 1 else: call_attempts[IMEI] = 1 # if key matches append mou else append 0. d[IMEI] = [running_MOU[IMEI]] d[IMEI].append([call_attempts[IMEI]]) d[IMEI].append([device]) print ,.join(header) for k,v in sorted(d.items()): print k, ,, d[k][print_map['MOU']],,, d[k][print_map['Call_Att']][0],,, d[k][print_map['Device']][0] print complete Here's an alternative that uses only one dict: import csv import os import sys header = ['IMEI', 'MOUs', 'Call_Att', 'Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' d = {} for fname in os.listdir(path): with open(os.path.join(path, fname)) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] elapsed_mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in d: record = d[IMEI] record[1] += elapsed_mins record[2] += 1 else: d[IMEI] = [IMEI, elapsed_mins, 1, device] writer = csv.writer(sys.stdout) writer.writerow(header) writer.writerows(sorted(d.itervalues())) print complete ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of lists
On 03/06/15 17:39, Chris Stinemetz wrote: I am trying to create a dictionary of lists as I read a file. I envision it looking like: {key: [float_type],[string_type]} Thats not a dictionary of lists. You maybe mean: {key: [[float_type],[string_type]]} Which is a dictionary of lists of lists? For the first item in the list I am trying to add the value to the existing value where the key matches Sorry, I'm sure that made sense to you but not to me. Which value are you adding to which existing value? Can you give a before/after example? Resetting execution engine Running C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py The Python REPL process has exited That's slightly unusual. How are you running this? Traceback (most recent call last): File C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py, line 22, in module d[IMEI] += Elapsed_Mins TypeError: 'float' object is not iterable d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace(', ) So IMEA is a string and Elapsed_Mins is a float and d is a default dict that sets its defaults to lists. d[IMEI] += Elapsed_Mins ## this is where the error occurs. So this is trying to add a float to a list. L = [] L += f Traceback (most recent call last): File stdin, line 1, in module TypeError: 'float' object is not iterable look familiar? Now, what I don't know, is what you are trying to do. Are you trying to append the float to the list? Or to replace the list with the float? Or to add the float to the value of the first(or last?) element in the list - if it exists (and if it doesn't? Then what?) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of lists
Resetting execution engine Running C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py The Python REPL process has exited That's slightly unusual. How are you running this? I am running it with Microsoft Visual Studio Community 2013 using Python Tools for Visual Studio Now, what I don't know, is what you are trying to do. Are you trying to append the float to the list? Or to replace the list with the float? Or to add the float to the value of the first(or last?) element in the list - if it exists (and if it doesn't? Then what?) Although I am certain it is not very efficient I was able to accomplish what I wanted with the following code I wrote: import os import pprint import csv from collections import defaultdict print_map = {'MOU':0, 'Call_Att':1, 'Device':2} header = ['IMEI','MOUs','Call_Att','Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' os.chdir(path) running_MOU = {} call_attempts = {} d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace(', ) if IMEI in running_MOU.keys(): running_MOU[IMEI] += Elapsed_Mins else: running_MOU[IMEI] = Elapsed_Mins if IMEI in call_attempts.keys(): call_attempts[IMEI] += 1 else: call_attempts[IMEI] = 1 # if key matches append mou else append 0. d[IMEI] = [running_MOU[IMEI]] d[IMEI].append([call_attempts[IMEI]]) d[IMEI].append([device]) print ,.join(header) for k,v in sorted(d.items()): print k, ,, d[k][print_map['MOU']],,, d[k][print_map['Call_Att']][0],,, d[k][print_map['Device']][0] print complete ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary keys
Alex Kleider wrote: On 2014-04-08 14:34, Peter Otten wrote: That's a change in Python 3 where dict.keys() no longer creates a list, but instead creates a view on the underlying dict data thus saving time and space. In the rare case where you actually need a list you can explicitly create one with ips = list(ipDic) Thanks, Peter, for this clarification. I want to present the list sorted so probably this is the rare case of which you spoke where I would need to use l = list(myDict) rather than the view. You can create and sort the list in a single step: l = sorted(myDict) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary keys
On 2014-04-08 23:55, Peter Otten wrote: You can create and sort the list in a single step: l = sorted(myDict) Thank you again; this is a new idiom for me. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary keys
Alex Kleider wrote: I've got a fairly large script that uses a dictionary (called 'ipDic') each value of which is a dictionary which in turn also has values which are not simple types. Instead of producing a simple list, ips = ipDic.keys() print(ips) yields dict_keys(['61.147.107.120', '76.191.204.54', '187.44.1.153']) Searching my code for 'dict_keys' yields nothing. I've no idea where it comes from. Can anyone shed light on why instead of getting the list I'm expecting I get dict_keys( list I'm expecting )? (Using Python3, on Ubuntu 12.4) That's a change in Python 3 where dict.keys() no longer creates a list, but instead creates a view on the underlying dict data thus saving time and space. In the rare case where you actually need a list you can explicitly create one with ips = list(ipDic) I've been unable to reproduce this behaviour using simpler dictionaries which seem to work as I expect: d = dict(a=1, b=2, c=3) d {'a': 1, 'c': 3, 'b': 2} d.keys() ['a', 'c', 'b'] print(d.keys()) ['a', 'c', 'b'] That's because the above is a session using Python 2. Compare: $ python3 Python 3.3.2+ (default, Feb 28 2014, 00:52:16) [GCC 4.8.1] on linux Type help, copyright, credits or license for more information. dict(a=1, b=2).keys() dict_keys(['b', 'a']) $ python2 Python 2.7.5+ (default, Feb 27 2014, 19:37:08) [GCC 4.8.1] on linux2 Type help, copyright, credits or license for more information. dict(a=1, b=2).keys() ['a', 'b'] PS: You can get a view in Python 2, too, with dict.viewkeys() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary keys
On 2014-04-08 14:34, Peter Otten wrote: That's a change in Python 3 where dict.keys() no longer creates a list, but instead creates a view on the underlying dict data thus saving time and space. In the rare case where you actually need a list you can explicitly create one with ips = list(ipDic) That's because the above is a session using Python 2. Compare: $ python3 Python 3.3.2+ (default, Feb 28 2014, 00:52:16) [GCC 4.8.1] on linux Type help, copyright, credits or license for more information. dict(a=1, b=2).keys() dict_keys(['b', 'a']) $ python2 Python 2.7.5+ (default, Feb 27 2014, 19:37:08) [GCC 4.8.1] on linux2 Type help, copyright, credits or license for more information. dict(a=1, b=2).keys() ['a', 'b'] PS: You can get a view in Python 2, too, with dict.viewkeys() Thanks, Peter, for this clarification. I want to present the list sorted so probably this is the rare case of which you spoke where I would need to use l = list(myDict) rather than the view. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary from a text file
Nitish Kunder wrote: I have a dictionary which is in this format for ex: { '5x' : { '50' : { 'update' : { 'update-from-esxi5.0-5.0_update01' : { 'call' : Update, 'name' : 'Update50u1', 'release' : '15/03/12' }, 'update-from-esxi5.0-5.0_update02' : { 'call' : Update, 'name' : 'Update50u2', 'release' : '21/12/12' }, }, 'patch' : { 'ESXi500-201109001' : { 'call' : Patch, 'name' :'Patch_501', 'release' : '13/09/11' }, 'ESXi500-20001' : { 'call' : Patch, 'name' :'ExpressPatch501', 'release' : '13/09/11' }, }, }, '51' : { 'update' : { 'update-from-esxi5.1-5.1_update01' : { 'call' : Update, 'name' : 'Update51u1', 'release' : '25/04/13' }, }, 'patch' : { 'ESXi510-201210001' : { 'call' : Patch, 'name' :'ExpressPatch511', 'release' : '29/08/13' }, 'ESXi510-201212001' : { 'call' : Patch, 'name' :'Patch_511', 'release' : '20/12/12' }, }, }, }, } Note: in* 'call' : Update* ,Update it is a function defined in my python script. My dictionary is too large so i taught rather than using directly in python program I save it in a text file and when needed i assign it to dictionary object . How can i assign this text file to dictionary object and call it? You could modify the dict a bit to comply with the json format and then load and post-process it to replace names with functions: import json def Update(): pass def Patch(): pass def post_process(x, names): for k, v in x.items(): if k == ucall: x[k] = names[v] elif isinstance(v, dict): post_process(v, names) with open(tmp.json) as instream: d = json.load(instream) post_process(d, names={uPatch: Patch, uUpdate: Update}) Another option is to use a function similar to ast.literal_eval() that can do name lookups. Here's my adaptation of literal_eval(): import ast def Update(): pass def Patch(): pass def safe_eval(s, names={}): node = ast.parse(s, mode=eval) if isinstance(node, ast.Expression): node = node.body def convert(node): if isinstance(node, ast.Str): return node.s elif isinstance(node, ast.Dict): return {convert(k): convert(v) for k, v in zip(node.keys, node.values)} elif isinstance(node, ast.Name): try: return names[node.id] except KeyError: raise ValueError(Unresolved name {!r}.format(node.id)) raise ValueError(Malformed node or string {!r}.format(node)) return convert(node) with open(tmp.txt) as instream: data = instream.read() d = safe_eval(data, dict(Update=Update, Patch=Patch)) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary from a text file
On 10/31/2013 2:16 AM, Nitish Kunder wrote: I have a dictionary which is in this format for ex: { '5x' : { '50' : { 'update' : { 'update-from-esxi5.0-5.0_update01' : { 'call' : Update, 'name' : 'Update50u1', 'release' : '15/03/12' }, 'update-from-esxi5.0-5.0_update02' : { 'call' : Update, 'name' : 'Update50u2', 'release' : '21/12/12' }, }, 'patch' : { 'ESXi500-201109001' : { 'call' : Patch, 'name' :'Patch_501', 'release' : '13/09/11' }, 'ESXi500-20001' : { 'call' : Patch, 'name' :'ExpressPatch501', 'release' : '13/09/11' }, }, }, [snip] Does it have to be in a dictionary format? I'd rather use sqlite to store the data. Also please give us a use case. There is probably a much simper and more elegant solution. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary from a text file
Note: in* 'call' : Update* ,Update it is a function defined in my python script. My dictionary is too large so i taught rather than using directly in python program I save it in a text file and when needed i assign it to dictionary object . How can i assign this text file to dictionary object and call it? To introduce some terms: you are serializing some data --- your dictionary --- to disk and back. There are a few libraries that help you do the hard work of translating the nested dictionary structure to some flat string; in addition, they almost always includes a parser to go back from that flat string back to the nested dictionary structure. The 'json' library that Petter Otten suggests is one of these serialization libraries. Try looking into that and see if you can just take advantage of it. Are there other consumers for this data besides just your program? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
On 20/03/13 14:54, Amit Saha wrote: Hello Phil, On Wed, Mar 20, 2013 at 12:54 PM, Phil phil_...@bigpond.com wrote: Thank you for reading this. I'm working my way through a series of exercises where the author only provides a few solutions. The reader is asked to modify the histogram example so that it uses the get method thereby eliminating the if and else statements. Histogram2 is my effort. The resulting dictionary only contains the default value provided by get and I cannot see how the value can be incremented without an if statement. You are almost there. Note that all you have to do is increment 1 to the current 'value' for the key denoted by c. If you change the line with get() to the following, it works as you want it to: d[c]= 1 + d.get(c, 0) Output: {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} histogram2 {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} You were almost there. Good Luck. -Amit. Thanks Amit and Mitya, I thought I must have been close. I've played with C++ since the mid 90s and I'm finding Python very refreshing. -- Regards, Phil ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
On 20/03/13 15:09, Mitya Sirenef wrote: cut By the way, you can further simplify it by doing: def histogram2(s): return {c: d.get(c,0)+1 for c in s} That will work in python 3, in python 2 you need: return dict((c: d.get(c,0)+1) for c in s) Thanks again Mitya, although I'm not sure it's a simplification at my present level. -- Regards, Phil ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
Phil wrote: On 20/03/13 15:09, Mitya Sirenef wrote: cut By the way, you can further simplify it by doing: def histogram2(s): return {c: d.get(c,0)+1 for c in s} That will work in python 3, in python 2 you need: return dict((c: d.get(c,0)+1) for c in s) Thanks again Mitya, although I'm not sure it's a simplification at my present level. Especially as Mitya's code doesn't work. {k: v for k, v in [(1, a), (2, b)]} {1: 'a', 2: 'b'} is called dict comprehension, it builds a dict from a list of key-value pairs. However, there is no way to reference the resulting dict while it is being built, and that is necessary for a histogram. It is possible to use dict.update() with a generator expression d = {} d.update((c, d.get(c, 0)+1) for c in abba) d {'a': 2, 'b': 2} but frankly, I don't see how that is better than the for loop. So as your experience with Python grows you may continue to use a loop or switch to the standard library's collections.Counter (Python3 only). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
On 03/20/2013 04:21 AM, Peter Otten wrote: Phil wrote: On 20/03/13 15:09, Mitya Sirenef wrote: cut By the way, you can further simplify it by doing: def histogram2(s): return {c: d.get(c,0)+1 for c in s} That will work in python 3, in python 2 you need: return dict((c: d.get(c,0)+1) for c in s) Thanks again Mitya, although I'm not sure it's a simplification at my present level. Especially as Mitya's code doesn't work. Ah, yes - I messed up here.. I agree the loop is the best option here, vs. the example below. -m d = {} d.update((c, d.get(c, 0)+1) for c in abba) d {'a': 2, 'b': 2} but frankly, I don't see how that is better than the for loop. So as your experience with Python grows you may continue to use a loop or switch to the standard library's collections.Counter (Python3 only). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
On 03/19/2013 10:54 PM, Phil wrote: Thank you for reading this. I'm working my way through a series of exercises where the author only provides a few solutions. The reader is asked to modify the histogram example so that it uses the get method thereby eliminating the if and else statements. Histogram2 is my effort. The resulting dictionary only contains the default value provided by get and I cannot see how the value can be incremented without an if statement. def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d def histogram2(s): d = dict() for c in s: d[c]= d.get(c, 0) return d h = histogram(brontosaurs) print h print print histogram2 h = histogram2(brontosaurs) print h Add + 1 -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Whenever you find yourself on the side of the majority, it is time to pause and reflect. Mark Twain ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
Hello Phil, On Wed, Mar 20, 2013 at 12:54 PM, Phil phil_...@bigpond.com wrote: Thank you for reading this. I'm working my way through a series of exercises where the author only provides a few solutions. The reader is asked to modify the histogram example so that it uses the get method thereby eliminating the if and else statements. Histogram2 is my effort. The resulting dictionary only contains the default value provided by get and I cannot see how the value can be incremented without an if statement. You are almost there. Note that all you have to do is increment 1 to the current 'value' for the key denoted by c. If you change the line with get() to the following, it works as you want it to: d[c]= 1 + d.get(c, 0) Output: {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} histogram2 {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} You were almost there. Good Luck. -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
On 03/19/2013 10:54 PM, Phil wrote: Thank you for reading this. I'm working my way through a series of exercises where the author only provides a few solutions. The reader is asked to modify the histogram example so that it uses the get method thereby eliminating the if and else statements. Histogram2 is my effort. The resulting dictionary only contains the default value provided by get and I cannot see how the value can be incremented without an if statement. def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d def histogram2(s): d = dict() for c in s: d[c]= d.get(c, 0) return d h = histogram(brontosaurs) print h print print histogram2 h = histogram2(brontosaurs) print h By the way, you can further simplify it by doing: def histogram2(s): return {c: d.get(c,0)+1 for c in s} That will work in python 3, in python 2 you need: return dict((c: d.get(c,0)+1) for c in s) -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Those who can make you believe absurdities can make you commit atrocities. Voltaire ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary get method
On 03/20/2013 01:09 AM, Mitya Sirenef wrote: By the way, you can further simplify it by doing: def histogram2(s): return {c: d.get(c,0)+1 for c in s} That will work in python 3, in python 2 you need: return dict((c: d.get(c,0)+1) for c in s) Sorry, it should use a comma: return dict((c, d.get(c,0)+1) for c in s) -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary
On 6/17/2012 2:26 PM, Selby Rowley-Cannon wrote: [snip] Do you have any programming (algorithm development) experience? Do you want to translate words independent of context? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary
Does this language have grammar independent of english? If no, just use .split() on the string and loop through that. If yes, well, its much more complicated On Jun 17, 2012 2:27 PM, Selby Rowley-Cannon selbyrowleycan...@ymail.com wrote: Version: 2.7 OS: Ubuntu 12.04 LTS I am writing a small translation app for Rydish (A language that exists in the same way Klingon does, invented by my company for a[n] RPG). Here is my current method of translation: Edictionary = {'English keys':'Rydish values'} TextEng = raw_input('Please enter your text: ') if TextEng in Edictionary: print(TextEng + ' traslates to ' + Edictionary[TextEng]) But I have found that this is only going to translate one word at a time. I thought about a loop of somesort, but I can't seem to find one that won't still force the user to translate one word at a time. Can anyone tell me how to translate a full sentance/several sentances? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of methods calling syntax
Alan Gauld wrote: Since a class is effectively a disguised dictionary I'm not sure why you want to do this? If you just want to access the method by name then why not just call getattr(spam,'get_mean')? Thanks for the feedback and, yes, this makes sense. My use case was when the statistic desired was going to be specified at runtime (through file input or UI) and that a dictionary would be a convenient crosswalk to associate the statistic name with the method name (and thus avoid an if/else ladder). But I understand that as long as there is a direct relationship between the name of the statistic and my class method (e.g. 'mean' - get_mean), that I should be able to use the getattr() syntax as above. Thanks also to Joel for the suggestion to put the dictionary inside of __init__. thanks, matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of methods calling syntax
On 08/02/2012 17:41, Gregory, Matthew wrote: Alan Gauld wrote: Since a class is effectively a disguised dictionary I'm not sure why you want to do this? If you just want to access the method by name then why not just call getattr(spam,'get_mean')? Thanks for the feedback and, yes, this makes sense. My use case was when the statistic desired was going to be specified at runtime (through file input or UI) and that a dictionary would be a convenient crosswalk to associate the statistic name with the method name (and thus avoid an if/else ladder). But I understand that as long as there is a direct relationship between the name of the statistic and my class method (e.g. 'mean' - get_mean), that I should be able to use the getattr() syntax as above. Thanks also to Joel for the suggestion to put the dictionary inside of __init__. thanks, matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This should help if you need more info http://code.activestate.com/lists/python-list/403361/ -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of methods calling syntax
On Tue, Feb 7, 2012 at 2:32 PM, Gregory, Matthew matt.greg...@oregonstate.edu wrote: Hi list, I'm trying to understand how to use a class-level dictionary to act as a switch for class methods. In the contrived example below, I have the statistic name as the key and the class method as the value. class Statistics(object): STAT = { 'MEAN': get_mean, 'SUM': get_sum, } def __init__(self, a, b): self.a = a self.b = b def get_mean(self): return (self.a + self.b) / 2.0 def get_sum(self): return (self.a + self.b) def get_stat(self, stat): f = self.STAT[stat.upper()] return f(self) if __name__ == '__main__': spam = Statistics(4, 3) print spam.get_stat('mean') print spam.get_stat('sum') When I try to run this, I get: NameError: name 'get_mean' is not defined If I move the STAT dictionary to the bottom of the class, it works fine. I understand why I get an error, i.e. when the dictionary is created get_mean hasn't yet been defined, but I'm wondering if there is a better common practice for doing this type of lookup. My web searches didn't come up with anything too applicable. thanks, matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You might want to read through this: http://stackoverflow.com/questions/5213166/python-forward-declaration-of-functions-inside-classes Specifically from an answer: First, in class B, the function foo() is called before being declared. A does not have this problem because foo() is only called when the class is instantiated--after the function foo is defined. So, I think you could move your STAT dictionary definition into the __init__ method so that is doesn't actually run until you create an instance of your class. That being said, I'm not sure that is more 'pythonic' than moving it to the bottom of the class definition -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary of methods calling syntax
On 07/02/12 19:32, Gregory, Matthew wrote: class Statistics(object): STAT = { 'MEAN': get_mean, 'SUM': get_sum, } ... if __name__ == '__main__': spam = Statistics(4, 3) print spam.get_stat('mean') print spam.get_stat('sum') Since a class is effectively a disguised dictionary I'm not sure why you want to do this? If you just want to access the method by name then why not just call getattr(spam,'get_mean')? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary to variable copy
Op 08-12-11 10:03, sunil tech schreef: /Can i copy the content if a dictionary in to another variable, with out any link between the dictionary the variable? / Have a look at the copy module [1], or use the builtin dict.copy() method. Cheers, Timo [1] http://docs.python.org/library/copy.html#module-copy / if so, please teach. / ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary to variable copy
On 08/12/11 09:03, sunil tech wrote: /Can i copy the content if a dictionary in to another variable, with out any link between the dictionary the variable? if so, please teach. Yes, but they will both refer to the same object. But the two references will be entirely independant: D = {1:2,3:4} d = D[1] # both d and D[1] reference 2 D[1] = 42 # d still refers to 2 del(D) # d still refers to 2 Is that what you mean? Or do you wantbto make a clone of the value so that you can change it without changing the original? In that case you can use several techniques depending on object type. Generically use copy or deepcopy. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary File character reader
On Tue, May 10, 2011 at 5:27 AM, Clara Mintz jamani.s...@hotmail.com wrote: Sorry I am completely new at python and don't understand why this function is returning an empty dictionary. I want it to take a list of files open them then return the number of characters as the value and the file name as the key. def fileLengths(files): d = {} files = [] Here's why. You take the name files and assign it to an empty list, so you lose the files that you sent to the function. files = [file_1.txt, file_2.doc] files ['file_1.txt', 'file_2.doc'] files = [] files [] You don't need that line at all, so remove it, and see what happens. :) for file in files: reader = open(file) for line in reader: char = sum(len(line)) As a side not, this doesn't need to be sum in this case - the len is simply len, throwing away what it previously was. In fact, this probably isn't what you want. At any one point, char is the length of a single line, not the sum of every length of every line in the file. What you want is something that takes the length of each line, and add it to the sum. A simple way would be to do sum(len(line) for line in file) d[file] = char reader.close return d Thank you sorry I don't understand what I am doing wrong. -Clara ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hope this helped. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary File character reader
Noah Hall enali...@gmail.com wrote What you want is something that takes the length of each line, and add it to the sum. A simple way would be to do sum(len(line) for line in file) And if you just want the total count for the file an even simpler way is to use file.read() count = len(file.read()) One other thing to consider is whether you want to include line feed characters in the count... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary File character reader
On 01/-10/-28163 02:59 PM, Clara Mintz wrote: Sorry I am completely new at python and don't understand why this function is returning an empty dictionary. I want it to take a list of files open them then return the number of characters as the value and the file name as the key. def fileLengths(files):d = {}files = []for file in files: reader = open(file)for line in reader:char = sum(len(line)) d[file] = charreader.closereturn d Thank you sorry I don't understand what I am doing wrong. -Clara The first thing you're doing is wordwrapping your program fragment. It makes the code hard to read, and some aspects impossible, as we can't tell what parts were indented by how much. The second thing is clobbering your input parameter. files=[] will obliterate whatever argument was passed to that function. You will have more problems after that: sum() won't work on an integer, so it's not clear why you're calling len() on the line. You're returning d from the function, but nothing in the function ever inserts anything into it. So it will clearly be empty. print is your friend. A couple of carefully placed print statements would reveal these problems. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary
Supposing your dictionary like this: dict={1:'My name is X',2:'My name is x y z',3: 'i am X'} You can use len(list) : dict={1:'My name is X',2:'My name is x y z',3: 'i am X'} for values in dict.values(): ... if len(values.split(' '))3: ...print values My name is X My name is x y z On Fri, May 6, 2011 at 7:56 AM, louis leichtnam l.leicht...@gmail.comwrote: HEllo everyone, I have a dictionnary, and I would like to print only the values that have more/equal than 3 spaces in them for example: My name is Xavier. Can you help me out, Thanks Louis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary
louis leichtnam wrote: HEllo everyone, I have a dictionnary, and I would like to print only the values that have more/equal than 3 spaces in them for example: My name is Xavier. d = {1: Hello world, 2: My name is Xavier, 3: ham and eggs, 4: Eat more cheese please!, 5: spam spam spam spam spam spam, 6: how much wood would a woodchuck chuck if a woodchuck would chuck wood?, 7: nice cup of tea and a slice of cake} for value in d.values(): if value.count( ) = 3: print(value) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
Garry Bettle wrote: Howdy all, Hope this message finds everyone well. I have dictionary of keys and a string of values. i.e. 8 Fixtures: I assume each fixture is a key, e.g. Swin, HGrn, etc. Swin1828 1844 1901 1916 1932 1948 2004 2019 2036 2052 2107 2122 HGrn1148 1204 1218 1232 1247 1304 1319 1333 1351 Newc1142 1157 1212 1227 1242 1258 1312 1327 1344 1403 Yarm1833 1849 1906 1922 1937 1953 2009 2024 2041 2057 2112 BVue1418 1437 1457 1517 1538 1558 1618 1637 1657 1717 1733 1747 1804 181 Hove1408 1427 1447 1507 1528 1548 1608 1627 1647 1707 1722 1738 1756 181 Romfd 1930 1946 2003 2019 2035 2053 2109 2125 2141 2157 2213 2230 Sund1839 1856 1911 1927 1943 1958 2014 2031 2047 2102 2117 I print that with the following: f = open(SummaryFile, 'a') header = %d Fixtures, %d Races:\n % len(FixtureDict.keys()) print header f.write(header) f.write(\n) for fixture, racetimes in FixtureDict.iteritems(): line = %s\t%s % (fixture, .join(racetimes)) According to your description, racetimes is already a single string, so using join on it would be the wrong thing to do: racetimes = 1839 1856 1911 .join(racetimes) '1 8 3 9 1 8 5 6 1 9 1 1' So what is racetimes? Is it a string, or is it a list of strings? ['1839', '1856', '1911'] I'm going to assume the latter. That's the right way to do it. print line f.write(line + \n) f.write(\n) f.close() What I'd like to is add the number of values to the Header line. So how would I get i.e. 8 Fixtures, 93 Races I tried header = %d Fixtures, %d Races:\n % (len(FixtureDict.keys()), len(FixtureDict.values())) But I get print header 8 Fixture, 8 Races Any ideas? You need len(racetimes) rather than len(FixtureDict.values()). Every dict has exactly one value for every key, always, without exception. That is, len(dict.keys()) == len(dict.values()). In this case, the values are lists of multiple start times, but each list counts as one value. You need to count the number of items inside each value, not the number of values. In this case, you need to sum the number of races for all the fixtures: num_races = sum(len(racetimes) for racetimes in FixtureDict.values()) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
On 12/22/2010 7:31 AM, Steven D'Aprano wrote: Also note: len(dict.keys()) == len(dict.values()) == len(dict) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Question
On Wed, 22 Dec 2010 23:31:39 +1100, Steven D'Aprano wrote: In this case, you need to sum the number of races for all the fixtures: num_races = sum(len(racetimes) for racetimes in FixtureDict.values()) Many thanks Steven for your explanation and final golden nugget of code. On Wed, 22 Dec 2010 10:11:25 -0500, bob gailer wrote: Also note: len(dict.keys()) == len(dict.values()) == len(dict) Yup, thanks Bob. Cheers, G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary and more
Hi- I apologize for the size of the attached file, but the question would make little sense if I made substantial deletions. The program gives the following error: Traceback (most recent call last): File /Javastuff/python/Glau_Is.py, line 131, in module Adestin[state]() TypeError: 'NoneType' object is not callable This is after the RETA prinout from function A_1, so that seems to be called correctly. The black screen is not part of the problem, I am not including the .jpeg files. Line 131 is the one that reads Adestin[state]() and the program prints (correctly) state=1 before the traceback. Thanks in advance for any insights. JLU Trust me. I have a lot of experience at this. General Custer's unremembered message to his men, just before leading them into the Little Big Horn Valley import pygame from pygame.locals import * from sys import exit import time import random from math import * global gamma gamma = .25 global RET RET = [0,0] global state global r def A_1(): state =1 r = 1 - gamma f = random.randrange(3) g = f+2 #destination RET = (g,r) print RETA!=, RET def A_2(): state = 2 global r2 r2 = 1. + gamma f = random.randrange(3) if f == 0: g = 1 #destination elif f == 1: g,r2 = 7,1. elif f == 2: g,r2 = 6,1 else: print alarm 2 RET = [g,r2] def A_3(): state =3 global r3 r3 = 1. + gamma f = random.randrange(3) if f == 1: g = 1 elif f == 0: g,r3 = 7, 1. elif f == 2: g, r3 = 5, 1 else: print alarm 3 RET = [g, r3] def A_4(): state = 4 global r4 r4 = 1. + gamma f = random.randrange(3) if f == 2: g = 1 elif f == 0: g,r4 = 6,1 elif f == 1: g,r4 = 5,1 else: print alarm 4 RET = [g, r4] def A_5(): state =5 global r5 r5 = 1. + gamma f = random.randrange(3) if f == 0: g = 8 elif f == 1: g,r5 = 4,1 elif f == 2: g,r5 = 3,1 else: print alarm 5 RET = [g, r5] def A_6(): state = 6 global r6 r6 = 1. + gamma f= random.randrange(3) if f == 1: g = 8 elif f == 0: g,r6 = 4,1 elif f == 2: g,r6 = 3,1 else: print alarm 6 RET = [g, r6] def A_7(): state = 7 global r7 r7 = 1. + gamma f = random.randrange(3) if f == 2: g = 8 elif f == 0: g,r7 = 3,1 elif f == 1: g,r7 = 2,1 else: print alarm 7 RET = [g, r7] def A_8(): state = 8 global r8 r8 = 1. - gamma f = random.randrange(3) g = f + 5 RET = [g, r8] #dictionaries Adestin = {1: A_1(), 2 : A_2(), 3 : A_3(), 4: A_4(),5 : A_5(), 6 : A_6(), 7: A_7(), 8 : A_8()} apics = {1: 'a_1.jpg', 2: 'a_2.jpg', 3 : 'a_3.jpg', 4: 'a_4.jpg', 5: 'a_5.jpg', 6: 'a_6.jpg', 7 : 'a_7.jpg', 8 : 'a_8.jpg'} state = 1 #set initial state pygame.init() screen = pygame.display.set_mode((640,480), 0, 32) pygame.event.pump() back1 =apics[state] back = pygame.image.load(back1).convert() screen.blit(back, (0,0)) pygame.display.update() RET=(1,1-gamma) k=0 while k = 5: k = k+1 back1 = apics[state] print state=, state Adestin[state]() print RET, k destin = RET[0] pois = RET[1] back = pygame.image.load(back1).convert() screen.blit(back, (0,0)) pygame.display.update() state = destin print state=,destin time.sleep(5) print end ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary and more
Jack Uretsky j...@hep.anl.gov wrote Please do not reply to an existing thread when starting a new topic. This messes up threaded newsreaders and several archives. Start a new topic with a newmessage. I apologize for the size of the attached file, but the question would make little sense if I made substantial deletions. The program gives the following error: Traceback (most recent call last): File /Javastuff/python/Glau_Is.py, line 131, in module Adestin[state]() TypeError: 'NoneType' object is not callable This says that Adestin[state] is None. So lets see how Adestin gets initialised Its a function call, which returns None. So Python is correct. You want to store the function names (more accurately the function objects) so you do not want the () after the name when you initialise the dictionary. Here is an example: def f1(): print 'f1' def f2(): print 'f2' dct = {'1': f1, '2': f2} # notice no parens, only a reference for key in dct: dct[key]() # use the parens here to call the func HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary and more
On 10/11/2010 9:19 AM Jack Uretsky said... Hi- I apologize for the size of the attached file, but the question would make little sense if I made substantial deletions. The program gives the following error: Traceback (most recent call last): File /Javastuff/python/Glau_Is.py, line 131, in module Adestin[state]() TypeError: 'NoneType' object is not callable This is after the RETA prinout from function A_1, so that seems to be called correctly. The black screen is not part of the problem, I am not including the .jpeg files. Line 131 is the one that reads Adestin[state]() and the program prints (correctly) state=1 before the traceback. Then Adestin[1] is None causing TypeError: 'NoneType' object is not callable. You can verify that by printing Adestin[1] where you're currently printing state. Then you'd discover that when you're building Adestin you're assigning the _results_ of the functions to your dictionary. You probably want to leave off the parens when declaring the functions. Further, your functions probably need to return something -- add return statements if you want the results. HTH, Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary and more
On Tue, 12 Oct 2010 03:19:22 am Jack Uretsky wrote: Hi- I apologize for the size of the attached file, but the question would make little sense if I made substantial deletions. The program gives the following error: Traceback (most recent call last): File /Javastuff/python/Glau_Is.py, line 131, in module Adestin[state]() TypeError: 'NoneType' object is not callable The question makes perfect sense without even looking at the attached file. Adestin[state] returns None, which you attempt to call as a function. The questions you should be asking yourself are: - what value am I expecting it to contain? - where in my code should that value be set? - why is it setting None instead? Armed with these three questions, you now know how to debug the problem yourself. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
Khalid Al-Ghamdi wrote: Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Are you maybe looking for `dc = {y:x for y,x in zip('khalid', range(6))}` ? -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
Lie Ryan lie.1...@gmail.com dixit: note that: [(y, x) for y in list(khalid) for x in range(6)] [('k', 0), ('k', 1), ('k', 2), ('k', 3), ('k', 4), ('k', 5), ('h', 0), ('h', 1), ('h', 2), ('h', 3), ('h', 4), ('h', 5), ('a', 0), ('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('l', 0), ('l', 1), ('l', 2), ('l', 3), ('l', 4), ('l', 5), ('i', 0), ('i', 1), ('i', 2), ('i', 3), ('i', 4), ('i', 5), ('d', 0), ('d', 1), ('d', 2), ('d', 3), ('d', 4), ('d', 5)] and when that big list is turned into a dict it gives: dict(_) {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} ... because a dict holds a single value per key, so last value overrides previous ones. Denis la vita e estrany http://spir.wikidot.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
Hugo Arts hugo.yo...@gmail.com dixit: bc = {y: x for x, y in enumerate(khalid)} Note that your output is like so: {'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3} The first character in your original string gets a zero, the second a one, so on and so forth. I'm hoping that's what you meant. If you really want this: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} I'm not sure how to do that programmatically. # first need a list of sorted chars # otherwise python cannot guess what order you mean: chars = sorted(list(khalid)) print chars# == ['a', 'd', 'h', 'i', 'k', 'l'] # enumerate gives a list of (index, value) pairs # from which you can construct a dict: #~ dc = {index:char for (index,char) in enumerate(chars)} # or (python version 3) dc = dict((index,char) for (index,char) in enumerate(chars)) print dc # == {0: 'a', 1: 'd', 2: 'h', 3: 'i', 4: 'k', 5: 'l'} Denis la vita e estrany http://spir.wikidot.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
On 12/5/2009 7:32 AM, Khalid Al-Ghamdi wrote: Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} are you sure you want this? {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} instead of: {'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3} for the former case, you can't, you can't guarantee any sort of ordering in dictionary. You should use ordered dictionary instead. For the latter case, it's easy with zip() dc={y:x for x, y in zip(khalid, range(6))} as for why python did that, it's because dictionary comprehension is supposed to have similar semantic with: dc = {x: y for x, y in lst} dc = dict( (x, y) for x, y in lst ) so this: dc={y:x for y in list(khalid) for x in range(6)} becomes: dc=dict( (y, x) for y in list(khalid) for x in range(6) ) note that: [(y, x) for y in list(khalid) for x in range(6)] [('k', 0), ('k', 1), ('k', 2), ('k', 3), ('k', 4), ('k', 5), ('h', 0), ('h', 1), ('h', 2), ('h', 3), ('h', 4), ('h', 5), ('a', 0), ('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('l', 0), ('l', 1), ('l', 2), ('l', 3), ('l', 4), ('l', 5), ('i', 0), ('i', 1), ('i', 2), ('i', 3), ('i', 4), ('i', 5), ('d', 0), ('d', 1), ('d', 2), ('d', 3), ('d', 4), ('d', 5)] and when that big list is turned into a dict it gives: dict(_) {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
On Fri, Dec 4, 2009 at 9:32 PM, Khalid Al-Ghamdi emailkg...@gmail.com wrote: Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks That dictionary comprehension is equivalent to the following code: dc = {} for x in range(6): for y in list(khalid): dc[y] = x This makes it clear what is wrong. The two for loops come out as nested, rather than zipped. The general fix for something like this is the zip function: bc = {x: y for x, y in zip(khalid, xrange(6))} However, in this case, the idiomatic way to write this would be the enumerate function: bc = {y: x for x, y in enumerate(khalid)} Note that your output is like so: {'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3} The first character in your original string gets a zero, the second a one, so on and so forth. I'm hoping that's what you meant. If you really want this: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} I'm not sure how to do that programmatically. The dict object prints its objects in no particular order, so figuring out that order is hard (and very likely implementation/platform dependent). My best guess was sorted(khalid, key=hash): {'a': 0, 'd': 1, 'i': 3, 'h': 2, 'k': 4, 'l': 5} close, but no cigar. Anyone who can think of a clever hack for this? Not that it's very useful, but fun. Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
On 12/4/2009 12:32 PM Khalid Al-Ghamdi said... Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} Try breaking this into pieces... First see what [(x,y) for y in in list(khalid) for x in range(6)] gets you, then see how that fits into dict(). To get where you want, take a look at zip'ing the two lists. (II don't remember -- s zip still in 3.1?) Emile I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
Khalid Al-Ghamdi wrote: Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks You're confused about what two for loops do here. It's basically a doubly-nested loop, with the outer loop iterating from k through d, and the inner loop iterating from 0 to 5. So there are 36 entries in the dictionary, but of course the dictionary overwrites all the ones with the same key. For each letter in the outer loop, it iterates through all six integers, and settles on 5. To do what you presumably want, instead of a doubly nested loop you need a single loop with a two-tuple for each item, consisting of one letter and one digit. dc = { y:x for y,x in zip(khalid, range(6)) } The output for this is: {'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3} Now, this isn't the same values for each letter as you expected, but I'm not sure how you came up with that particular order.I expect, and get, 0 for the first letter 'k' and 1 for the 'h'. etc. Perhaps printing out the zip would make it clearer: list( zip(khalid, range(6)) ) yields [('k', 0), ('h', 1), ('a', 2), ('l', 3), ('i', 4), ('d', 5)] DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary, integer, compression
Dinesh B Vadhia dineshbvad...@hotmail.com wrote Say, you have a dictionary of integers, are the integers stored in a compressed integer format or as integers ie. are integers encoded before being stored in the dictionary and then decoded when read? I can't think of any reason to compress them, I imagine they are stored as integers. But given the way Python handlers integers with arbitrarily long numbers etc it may well be more complex than a simple integer (ie 4 byte number). But any form of compression would be likely to hit performamce so I doubt that they would be compressed. Is there anything that made you think they might be? HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary, integer, compression
Dinesh B Vadhia wrote: Say, you have a dictionary of integers, are the integers stored in a compressed integer format or as integers ie. are integers encoded before being stored in the dictionary and then decoded when read? Integer objects are not special cased in dictionaries. They are stored as normal int/long objects. Dictionaries do not use any kind of compression in Python. Stefan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary, integer, compression
Alan I want to perform test runs on my local machine with very large numbers of integers stored in a dictionary. As the Python dictionary is an built-in function I thought that for very large dictionaries there could be compression. Done correctly, integer compression wouldn't affect performance but could enhance it. Weird, I know! I'll check in with the comp.lang.python lot. Dinesh Message: 3 Date: Wed, 29 Apr 2009 17:35:53 +0100 From: Alan Gauld alan.ga...@btinternet.com Subject: Re: [Tutor] Dictionary, integer, compression To: tutor@python.org Message-ID: gt9vl7$oh...@ger.gmane.org Content-Type: text/plain; format=flowed; charset=iso-8859-1; reply-type=original Dinesh B Vadhia dineshbvad...@hotmail.com wrote Say, you have a dictionary of integers, are the integers stored in a compressed integer format or as integers ie. are integers encoded before being stored in the dictionary and then decoded when read? I can't think of any reason to compress them, I imagine they are stored as integers. But given the way Python handlers integers with arbitrarily long numbers etc it may well be more complex than a simple integer (ie 4 byte number). But any form of compression would be likely to hit performamce so I doubt that they would be compressed. Is there anything that made you think they might be? HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary looping problem
On Tue, Dec 02, 2008 at 01:08:09PM -0800, Jeremiah Jester wrote: Hello, I'm trying to gather a list of files and md5 hash them to do a checksum. I've created a function for each dictionary. However, when i print out the dictionary I don't get all the items. Any ideas? Yep. Don't use os.system() there. 1. you're running the md5 program externally when you don't need to, since Python has the ability to compute md5 checksums on its own, which you already know because you imported that module at the top of your script (and then didn't use). 2. The return value from os.system() is NOT the hash, so what you're storing in the dictionary is not going to be that unique, and so each call which yields the same return value (0, usually) will overwrite that element in the dict. -- Steve Willoughby| Using billion-dollar satellites [EMAIL PROTECTED] | to hunt for Tupperware. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor