3

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.

1
  • in addition to @rfj001's answer, this link has a nice concise explanation Commented Nov 21, 2015 at 6:40

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

msg = MIMEText(fp.read()) this code was used to take the string.How is that 'msg' acting as a dictionary now?
The 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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.