I am new to python and after learning some topics i wanted to do a small project (an email sender).When i was researching a bit about libraries needed and some examples, I saw the following piece of code :
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
I am confused about the syntax:
var['something'] = anything
What does this syntax imply? Please help.
-
in addition to @rfj001's answer, this link has a nice concise explanationhammus– hammus2015年11月21日 06:40:07 +00:00Commented Nov 21, 2015 at 6:40
2 Answers 2
This sort of syntax is used for accessing/modifying Python dictionaries. The example var["Something"] = anything is setting the value of the variable anything in the dictionary var for the key "Something"
Keys must be immutable objects, such as strings, integers, floating-point numbers, or tuples. Dictionary values can be any python object.
2 Comments
MIMEText(fp.read()) function has a dictionary as a return value. The dictionary generated is formatted to be sent as an email. The value for the "Subject" key specifies the subject of the email, the value for the "From" key specifies the sender email address, and the value for the "To" key specifies the email addresses to send the message to. The body of the email would contain the contents of the file pointed to by the file pointer fp.This syntax is used for python data structure dictionary which much like telephone dictionary enables us to associate a keyword (in square brackets) with a value (on LHS). For more details, please refer to section 5.5 in tutorial https://docs.python.org/2/tutorial/datastructures.html