[Tutor] creating dictionary from a list

Steven D'Aprano steve at pearwood.info
Sun Apr 14 03:36:31 CEST 2013


On 14/04/13 03:38, Saad Javed wrote:

> What just happened here? :)
>
> I am trying to learn python so i'm sorry if my mistakes seem trivial.


I have to ask the same question -- what just happened here? Why are you
upset? Mark has given you some good advice, and even added some
light-hearted joviality about somebody fighting an actual python in
real life.

Mark's advice about not "fighting" Python the language is excellent advice,
but of course as a beginner you aren't expected to know what are the most
natural ways to write Python code. If Mark had just stopped there, you
would have reason to be annoyed. But he didn't, he gave you some ideas for
how to re-write the code to be more "Pythonic" (natural for the language).

Mark is correct -- you will very rarely need to use indexing in a for-loop.

# don't do this
for i in range(len(some_list)):
      value = some_list[i]
      process(value)


# instead do this
for value in some_list:
      process(value)


When you need both the value and the index, the most Pythonic way to do so
is to use the built-in function "enumerate":

for index, value in enumerate(some_list):
     some_list[index] = process(value)


Also, beware your email program, whatever it is (Outlook?). It has the
unfortunate habit of adding extra characters into the text. Mark wrote
these six lines:

# there are no asterisks or underscores in the following:
for item in lst:
     if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
         myDict[item] = []
         saveItem = item
     else:
         myDict[saveItem].append(item.strip())


but by the time it came back from you quoted, it contains extra asterisks
added:


# mangled by your email client, three lots of double asterisks added:
for item in lst:
     if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
         myDict[item] = []
         saveItem = item
     else:
         myDict[saveItem].append(item.**strip())


and in a later email from you, somehow those asterisks had turned into
underscores! So beware of email clients that try to be "clever", and
mangle what is written.



-- 
Steven


More information about the Tutor mailing list