Re: [Tutor] write dictionary to file

2014-06-23 Thread Ian D
I will read this when I get a minute, but I must say thanks for the explanation.
 
tutor@python really is the most helpful mailing list EVER!
 
> Date: Tue, 24 Jun 2014 00:54:30 +1000
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] write dictionary to file
> 
> On Mon, Jun 23, 2014 at 09:17:44AM +, Ian D wrote:
> 
> > > for row in spamreader:
> > > if row['year'] == '40':
> > > email = row['user'] + '@email.com'
> > > output = [ row[fieldname] for fieldname in fields ]
> > 
> > I am unsure about this syntax [ row[fieldname] for fieldname in fields ]
> 
> 
> That's called a "list comprehension". It is a way of building up a list 
> as a single expression. Let's start with the old-fashioned way to build 
> a list:
> 
> output = []
> for fieldname in fields:
> output.append( row[fieldname] )
> 
> 
> Or, we can do exactly the same thing, in a single line, with a list 
> comprehension, and get rid of the temporary variables:
> 
> output = [row[fieldname] for fieldname in fields]
> 
> If you remember your high school maths classes, the form of the list 
> comp is rather close to that of mathematical set builder notation:
> 
> http://www.mathsisfun.com/sets/set-builder-notation.html
> 
> Here is a set builder notation, and its English translation:
> 
> {2n+1 : n ∈ {1,2,3,4}}
> 
> This reads as "the set of 2n plus 1, such that n is an element of 
> {1,2,3,4}". Don't be confused by the fact that there is a set inside a 
> set -- this just tells us how to build a new set from an old set.
> 
> So we start with a set {1,2,3,4}, and let n equal each of those numbers 
> in turn. Then we calculate 2n+1, and use that inside the new set we're 
> creating:
> 
> n = 1, so 2n+1 => 3
> n = 2, so 2n+1 => 5
> n = 3, so 2n+1 => 7
> n = 4, so 2n+1 => 9
> 
> and so the final result is the set {3, 5, 7, 9}.
> 
> Enough about sets and mathematics! Now we're going to talk about Python! 
> Python uses the same sort of expression, except it builds a list, not a 
> set, and calls it a "list comprehension" instead of a "list builder". 
> (Don't blame me for that, blame the Haskell programming language which 
> invented this.)
> 
> So, we start with the mathematical set builder:
> 
> {2n+1 : n ∈ {1,2,3,4}}
> 
> 
> Turn the sets into lists:
> 
> [2n+1 : n ∈ [1,2,3,4]]
> 
> 
> Use Python syntax for the formula:
> 
> [2*n+1 : n ∈ [1,2,3,4]]
> 
> 
> Replace the "such that" and "element of" with "for" "in":
> 
> [2*n+1 for n in [1,2,3,4]]
> 
> 
> and now you have a Python list comprehension. If you copy and paste that 
> into a Python interpreter, you'll see this:
> 
> py> [2*n+1 for n in [1,2,3,4]]
> [3, 5, 7, 9]
> 
> 
> 
> > > # DictWriter needs a dict, not a list.
> > > spamwriter.writerow({name: row[name] for name in fields})
> > 
> > And this writerow syntax is something new for me, as are dictionaries
> > (which I have tried to read up and understand.)
> 
> List comprehensions were added to Python in, I think, version 2.2, which 
> was about ten years ago. They turned out to be so useful and popular 
> that now, in Python 3, we have FOUR different kinds of "comprehensions" 
> or builder syntax:
> 
> List comprehensions:
> [2*n+1 for n in [1,2,3,4]]
> 
> Generator expressions (like a list comp, except values are created 
> lazily on demand, rather than all at once):
> (x+1 for x in [2, 4, 6, 8])
> 
> Set comprehensions (like a list comp, except it builds a set rather than 
> a list):
> {char.lower() for char in "Hello World!"}
> 
> Dict comprehensions (like a list comp, except it builds a dictionary of 
> key:value pairs):
> {char: char.lower() for char in "Hello World!"}
> 
> 
> So what is a dict? A dict, short for dictionary, is a table of keys with 
> associated values. Think of them as being like words and definitions:
> 
> words = { 
>   "cat": "a small mammal that purrs",
>   "dog": "man's best friend",
>   "snake": "a lizard with no legs",
>   "ostrich": "biggest bird in the world"
>   }
> 
> 
> The first part, before the colon, is the key. The part after the colon 
> is the value associated with that key. If you want to know the meaning 
> of a word, you look it up in the dictionary:
> 
> py> print(words['dog'])
> man's best friend
> 
> 
> To add a new word:
> 
> py> words['kangeroo'] = 'jumping marsupial from Australia'
> py> print(words['kangeroo'])
> jumping marsupial from Australia
> 
> 
> So I've already shown you the dict comprehension form:
> 
> spamwriter.writerow({name: row[name] for name in fields})
> 
> 
> Here is how we can do it the old-fashioned way without a dict comp:
> 
> 
> table = {}
> for name in fields:
> value = row[name]
> table[name] = value
> 
> spamwriter.writerow(table)
> 
> 
> 
> 
> Does this help? Ask any further questions you may have.
> 
> 
> 
> 
> 
> -- 
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subs

Re: [Tutor] write dictionary to file

2014-06-23 Thread Steven D'Aprano
On Mon, Jun 23, 2014 at 09:17:44AM +, Ian D wrote:

> > for row in spamreader:
> > if row['year'] == '40':
> > email = row['user'] + '@email.com'
> > output = [ row[fieldname] for fieldname in fields ]
> 
> I am unsure about this syntax [ row[fieldname] for fieldname in fields ]


That's called a "list comprehension". It is a way of building up a list 
as a single expression. Let's start with the old-fashioned way to build 
a list:

output = []
for fieldname in fields:
output.append( row[fieldname] )


Or, we can do exactly the same thing, in a single line, with a list 
comprehension, and get rid of the temporary variables:

output = [row[fieldname] for fieldname in fields]

If you remember your high school maths classes, the form of the list 
comp is rather close to that of mathematical set builder notation:

http://www.mathsisfun.com/sets/set-builder-notation.html

Here is a set builder notation, and its English translation:

{2n+1 : n ∈ {1,2,3,4}}

This reads as "the set of 2n plus 1, such that n is an element of 
{1,2,3,4}". Don't be confused by the fact that there is a set inside a 
set -- this just tells us how to build a new set from an old set.

So we start with a set {1,2,3,4}, and let n equal each of those numbers 
in turn. Then we calculate 2n+1, and use that inside the new set we're 
creating:

n = 1, so 2n+1 => 3
n = 2, so 2n+1 => 5
n = 3, so 2n+1 => 7
n = 4, so 2n+1 => 9

and so the final result is the set {3, 5, 7, 9}.

Enough about sets and mathematics! Now we're going to talk about Python! 
Python uses the same sort of expression, except it builds a list, not a 
set, and calls it a "list comprehension" instead of a "list builder". 
(Don't blame me for that, blame the Haskell programming language which 
invented this.)

So, we start with the mathematical set builder:

{2n+1 : n ∈ {1,2,3,4}}


Turn the sets into lists:

[2n+1 : n ∈ [1,2,3,4]]


Use Python syntax for the formula:

[2*n+1 : n ∈ [1,2,3,4]]


Replace the "such that" and "element of" with "for" "in":

[2*n+1 for n in [1,2,3,4]]


and now you have a Python list comprehension. If you copy and paste that 
into a Python interpreter, you'll see this:

py> [2*n+1 for n in [1,2,3,4]]
[3, 5, 7, 9]



> > # DictWriter needs a dict, not a list.
> > spamwriter.writerow({name: row[name] for name in fields})
> 
> And this writerow syntax is something new for me, as are dictionaries
> (which I have tried to read up and understand.)

List comprehensions were added to Python in, I think, version 2.2, which 
was about ten years ago. They turned out to be so useful and popular 
that now, in Python 3, we have FOUR different kinds of "comprehensions" 
or builder syntax:

List comprehensions:
[2*n+1 for n in [1,2,3,4]]

Generator expressions (like a list comp, except values are created 
lazily on demand, rather than all at once):
(x+1 for x in [2, 4, 6, 8])

Set comprehensions (like a list comp, except it builds a set rather than 
a list):
{char.lower() for char in "Hello World!"}

Dict comprehensions (like a list comp, except it builds a dictionary of 
key:value pairs):
{char: char.lower() for char in "Hello World!"}


So what is a dict? A dict, short for dictionary, is a table of keys with 
associated values. Think of them as being like words and definitions:

words = { 
  "cat": "a small mammal that purrs",
  "dog": "man's best friend",
  "snake": "a lizard with no legs",
  "ostrich": "biggest bird in the world"
  }


The first part, before the colon, is the key. The part after the colon 
is the value associated with that key. If you want to know the meaning 
of a word, you look it up in the dictionary:

py> print(words['dog'])
man's best friend


To add a new word:

py> words['kangeroo'] = 'jumping marsupial from Australia'
py> print(words['kangeroo'])
jumping marsupial from Australia


So I've already shown you the dict comprehension form:

spamwriter.writerow({name: row[name] for name in fields})


Here is how we can do it the old-fashioned way without a dict comp:


table = {}
for name in fields:
value = row[name]
table[name] = value

spamwriter.writerow(table)




Does this help? Ask any further questions you may have.





-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-23 Thread Ian D
Ok I used :


spamwriter.writerow({'user':email,'first':row['first'],'last':row['last'], 
'password':row['password'] })


Seems to be almost finished thanks


> From: dux...@hotmail.com
> To: tutor@python.org
> Date: Mon, 23 Jun 2014 09:17:44 +
> Subject: Re: [Tutor] write dictionary to file
>
>
>>>
>>> import csv
>>>
>>> csvfile= open('StudentListToSort.csv', newline='')
>>> spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|')
>>
>> Are you sure that your input file uses | as a quote character and , as
>> the field delimiter?
>
>
> No I overlooked this
>
>
>>
>>
>>> #open a file to write to later
>>> fields = ['user','first','last','password','year']
>>> csvoutput = open('output.csv', 'wb+')
>>
>> I'm pretty sure you don't want to use "wb+" mode. Since you're using
>> Python 3, I think you should just use "w" mode.
>>
>> The "b" turns on binary mode, and in Python 3 you don't want that. The
>> "+" turns on either "read/write" mode or "append" mode, I don't remember
>> which, but either way I don't think it's necessary for what you are
>> doing.
>
>
> Yes I came across this python 3 idiosyncrasy
>
>
>
>>
>>
>>> spamwriter = csv.DictWriter(csvoutput,fieldnames=fields, delimiter=' ')
>>
>> Now you're turning every , delimiter into a space. Are you sure you want
>> that?
>>
>>
>
>
> Overlooked this
>
>
>
>>> for row in spamreader:
>>> if row['year'] == '40':
>>> username = row['user']
>>> email = "".join([username,'@email.com])
>>
>> Syntax error: you left out the closing single quote. You need:
>>
>> email = "".join([username,'@email.com'])
>>
>
>
> I think I may have messed that up editing code for public viewing.
>
>
>
>
> On to your example.
>
>
>
>>
>> import csv
>>
>> # Open the file we're reading from.
>> csvfile= open('StudentListToSort.csv', newline='')
>> # Open a file to write to.
>> csvoutput = open('output.csv', 'w', newline='')
>>
>> fields = ['user', 'first', 'last', 'password', 'year']
>>
>> # Are you sure you want | as the quote character?
>> spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='|')
>
>>
>>
>> # Still using , as a delimiter, not space.
>> spamwriter = csv.DictWriter(csvoutput, fieldnames=fields, delimiter=',')
>>
>> for row in spamreader:
>> if row['year'] == '40':
>> email = row['user'] + '@email.com'
>> output = [ row[fieldname] for fieldname in fields ]
>
>
> I am unsure about this syntax [ row[fieldname] for fieldname in fields ]
>
>
>
> The FOR loop is not in any context I have used before. I have seen 
> examples(recently) so its obviously standard practice, but not something I 
> would ever think to type.
>
>
>
>> print(output)
>> # DictWriter needs a dict, not a list.
>> spamwriter.writerow({name: row[name] for name in fields})
>> print("Warning: email calculated but never used:", email)
>
>
>
>
> And this writerow syntax is something new for me, as are dictionaries( which 
> I have tried to read up and understand.)
>
>
>
>>spamwriter.writerow({name: row[name] for name in fields})
>
>
>
> This looks like the same loop as the one above but a dictionary using curly 
> braces(for dict), its the same unfamiliar way of writing a FOR loop for me.
>
>
>
>
> So if I wanted multiple rows in the output csv file I would try:
>
>
> ({name: row[name], row[email, row[first] for name in fields})
>
>
> which doesn't work as the syntax is invalid, so what would I need to change 
> to allow spamwriter.writerow to generate multiple fields?
> ___
> 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] write dictionary to file

2014-06-23 Thread Peter Otten
Ian, take a step back; the first step to solve a problem is to state it 
clearly. You want to write a dict to a file.

(1) What would the dictionary look like? Give concrete example, e. g.

{"foo": 42, "bar": 'that\'s not "funny"'}

(2) What should the resulting file look like when you open it in a text 
editer? Example:

foo,bar
42,"that's not ""funny"""

Only then you should proceed to write code.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regarding NDEF URL transfer to arduino using python

2014-06-23 Thread Alan Gauld

On 23/06/14 06:56, Shreyas Mangalgi wrote:

I want to be able to send URI in NDEF format to my Arduino UNO which is
connected to Sony's RC-S801 dynamic NFC tag.


I have no idea what most of that means in practice.
This looks very Arduino specific so you will probably get better results 
asking on an Arduino forum rather than a Python language list.

However...


utility to send

|"10010100031b0030d102165370d1011255017374757474676172742e736f6e792e646500"|


This is a string of hex digits.
Do you mean to send the character representations of the hex or do you 
mean to send the actual hex digits?



arduino=  serial.Serial('COM6',  115200)
arduino.parity=  'M'
print  arduino
print("writing")
input= 
("10010100031b0030d102165370d1011255017374757474676172742e736f6e792e646500")


You don't need the parentheses, they do nothing here.
But again this is a string representation of the hex data,
is that really what you want?


It shows as an empty record.Can you suggest changes to my python code
that I should make in order to detect the NDEF message ?Here is the
screenshot of the message that I get when I read the tag from my phone:

http://i.imgur.com/xn78Sw1.png


Posting images on a text based mailing list is not usually helpful.
If you can post the text of the message that is better.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] write dictionary to file

2014-06-23 Thread Ian D

>>
>> import csv
>>
>> csvfile= open('StudentListToSort.csv', newline='')
>> spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|')
>
> Are you sure that your input file uses | as a quote character and , as
> the field delimiter?


No I overlooked this


>
>
>> #open a file to write to later
>> fields = ['user','first','last','password','year']
>> csvoutput = open('output.csv', 'wb+')
>
> I'm pretty sure you don't want to use "wb+" mode. Since you're using
> Python 3, I think you should just use "w" mode.
>
> The "b" turns on binary mode, and in Python 3 you don't want that. The
> "+" turns on either "read/write" mode or "append" mode, I don't remember
> which, but either way I don't think it's necessary for what you are
> doing.


Yes I came across this python 3 idiosyncrasy



>
>
>> spamwriter = csv.DictWriter(csvoutput,fieldnames=fields, delimiter=' ')
>
> Now you're turning every , delimiter into a space. Are you sure you want
> that?
>
>


Overlooked this



>> for row in spamreader:
>> if row['year'] == '40':
>> username = row['user']
>> email = "".join([username,'@email.com])
>
> Syntax error: you left out the closing single quote. You need:
>
> email = "".join([username,'@email.com'])
>


I think I may have messed that up editing code for public viewing.




On to your example.



>
> import csv
>
> # Open the file we're reading from.
> csvfile= open('StudentListToSort.csv', newline='')
> # Open a file to write to.
> csvoutput = open('output.csv', 'w', newline='')
>
> fields = ['user', 'first', 'last', 'password', 'year']
>
> # Are you sure you want | as the quote character?
> spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='|')

>
>
> # Still using , as a delimiter, not space.
> spamwriter = csv.DictWriter(csvoutput, fieldnames=fields, delimiter=',')
>
> for row in spamreader:
> if row['year'] == '40':
> email = row['user'] + '@email.com'
> output = [ row[fieldname] for fieldname in fields ]


I am unsure about this syntax [ row[fieldname] for fieldname in fields ]

 

The FOR loop is not in any context I have used before. I have seen 
examples(recently) so its obviously standard practice, but not something I 
would ever think to type. 



> print(output)
> # DictWriter needs a dict, not a list.
> spamwriter.writerow({name: row[name] for name in fields})
> print("Warning: email calculated but never used:", email)


 

And this writerow syntax is something new for me, as are dictionaries( which I 
have tried to read up and understand.)

 

>spamwriter.writerow({name: row[name] for name in fields})

 

This looks like the same loop as the one above but a dictionary using curly 
braces(for dict), its the same unfamiliar way of writing a FOR loop for me.


 

So if I wanted multiple rows in the output csv file I would try:


({name: row[name], row[email, row[first] for name in fields})


which doesn't work as the syntax is invalid, so what would I need to change to 
allow spamwriter.writerow to generate multiple fields?  
   
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] write dictionary to file

2014-06-23 Thread Ian D
Thanks a lot this is really helpful as have been the other posts.


>
> Have you tried reading the documentation? It sounds like you're just
> throwing random bits of code at it and hoping something works.
>
> A better approach is to slow down and try to understand what the csv is
> doing, what it expects from you, and how you can best use it. Ask
> *focused* questions, rather than just blast us with blobs of code over
> and over again.
>



I do actually try and read this stuff and understand it, but when its new it 
really is not so simple.


When you already have a sound footing and experience it becomes elementary and 
its hard to understand why you could not understand it in the first place.


Admittedly I do usually try and botch together code from examples. When working 
for solutions sometimes time becomes an issue, and sometimes shortcuts pay off, 
but in the long run they never really do.


I appreciate your patience and your help I am going to try this example now 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Strange issue output not showing up as floats

2014-06-23 Thread Alan Gauld

On 23/06/14 01:32, Deb Wyatt wrote:


In future post real code, real output and real errors.
That way we have some chance of helping you.
--

I know, i'm sorry.  I was avoiding posting the actual

> code because it was an assignment,

Its even more important for assignments because without real
code we will tend to assume you haven't tried to do it. If
we can see that you have made a real attempt to solve it
then we will help fix the problem. So always post the
relevant code.


I was really hoping the moderator would see the second

> message and not send either message to the group.

Unfortunately the second came in just after I'd sent the first...


How long does it take to get off of moderation?


Until I notice that somebody is cropping up regularly. :-)
You are now off moderation.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] Regarding NDEF URL transfer to arduino using python

2014-06-23 Thread Shreyas Mangalgi
I want to be able to send URI in NDEF format to my Arduino UNO which is
connected to Sony's RC-S801 dynamic NFC tag.I used Hercules setup utility
to send

"10010100031b0030d102165370d1011255017374757474676172742e736f6e792e646500"

for http://www.stuttgart.sony.de and I was able to read it from my NFC
enabled phone.But when I used the following python code, it didn't work :

import serialimport time

arduino = serial.Serial('COM6', 115200)
arduino.parity = 'M'print arduino

print("writing")

input =
("10010100031b0030d102165370d1011255017374757474676172742e736f6e792e646500")

arduino.write(input)


time.sleep(5)print("stopped writing")



arduino.close()

It shows as an empty record.Can you suggest changes to my python code that
I should make in order to detect the NDEF message ?Here is the screenshot
of the message that I get when I read the tag from my phone:

http://i.imgur.com/xn78Sw1.png
Thanks
Shreyas
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Strange issue output not showing up as floats

2014-06-23 Thread Deb Wyatt
> 
> Not if you don't show us your code!
> 
>  > never mind.  I figured it out.  I was using %d instead
>  > of %f in my print statements.  duh.
> 
> 'duh', indeed but how could we possibly have helped since
> you didn't post any print statements?
> 
> In future post real code, real output and real errors.
> That way we have some chance of helping you.
> 
> --
I know, i'm sorry.  I was avoiding posting the actual code because it was an 
assignment,
and I did not want this to be construed as cheating. I was just looking for 
possible ideas
of what could possibly be wrong, but not posting the print statement made it 
impossible
for any of you to see my 'duh' error.

I was really hoping the moderator would see the second message and not send 
either message to the group.  How long does it take to get off of moderation?


Deb in WA, USA


FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!
Check it out at http://www.inbox.com/earth


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor