8159

Python keyword output interpretation

I'm going through the Python 2.7 tutorial, and I was looking at the output of the following statement:

def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw]

So, if I call the program as such:

cheeseshop("Cheddar", "No.", "Seriously?", Shopkeeper="Michael Palin", Client="John Cleese")

It outputs:

Do you have any Cheddar?
I'm sorry, we're all out of Cheddar
No.
Seriously?
--------------------------------------
Client: John Cleese
Shopkeeper: Michael Palin


This is correct.

If I change that print statement to print keywords, I get the following representation:

{'Shopkeeper': 'Ryan Lambert', 'Client': 'John Cleese'}

I'm a bit confused on how printing keywords[kw] just comes back with a name, and keywords does not.

Answer1:

In Python, you can pass optional keyword parameters by putting a ** in front of the function parameter's list.

So the keywords variable is actually a dictionary type. Thus, if you do:

print keywords

you get back (reformatted to make the mapping more obvious)

{ 'Shopkeeper': 'Ryan Lambert', 'Client': 'John Cleese' }

which is a dictionary. And if you do:

print keywords[kw]

you get back the value of the dictionary associated with the key kw. So if kw was 'Shopkeeper', then keywords[kw] becomes 'Ryan Lambert', and if kw was 'Client', then keywords[kw] becomes 'John Cleese'

Answer2:

keywords is stored as a dictionary. ( See this for more)

If you print the dictionary itself it is going to output the complete set of pairs it contains (key,value).

On your program:

    <li>keys are: 'Shopkeeper' and 'Client'</li> <li>values are respectively: 'Ryan Lambert' and 'John Cleese'</li> </ul>

    One way to access the values is to "search" for it with its key: dict[key]

    So when you wrote: "keywords[kw]" you are actually passing a key and python is going to give you the corresponding value.

    You can think it as similar as accessing an array value:

    a = ['a', 'b', 'c']

    if you:

    print a #output: ['a', 'b', 'c'] print a[0] # outputs: 'a'

    just unlike arrays the data is not stored "neatly" together in memory, but using hashing

    Hope it helped, Cheers

    Answer3:

    When you call the function with

    cheeseshop("Cheddar", "No.", "Seriously?", Shopkeeper="Michael Palin", Client="John Cleese")

    the keywords parameter takes on the value {'Shopkeeper': 'Ryan Lambert', 'Client': 'John Cleese'}, i.e., it's a dictionary.

    This is equivalent to (and much easier to read than) calling the function as

    cheeseshop("Cheddar", *["No.", "Seriously?"], **{"Shopkeeper":"Michael Palin", "Client":"John Cleese"})

    That is, the values in the first function call are automatically wrapped inside the *arguments and **keywords parameters -- that's what those * and ** are for.

    Now, when you do this:

    keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw]

    keyword.keys() is ['Shopkeeper', 'Client'], i.e. the "keys" in the dictionary. Next, you sort those keys and for each key, you print the respective entry in the dictionary, e.g., "John Cleese" for "Client".

Recommend

  • Rails 3.2.8. Upgrade checkboxes from Rails 1.x.x to 3.2.8
  • Twitter logout using oauth in iphone
  • How to printk the first 34 bytes (Ethernet and IP headers) of each packet (EtherType: 0x0806, Protoc
  • How to specify compression for custom build environment in Ember
  • Web API Help Pages - User-specific response type
  • append php in jquery
  • Test if a range intersects another range of numbers
  • My PHP newline beginner code isn't going to a new line. Little help?
  • Handlebars condition based on lookup
  • How to visualize output of intermediate layers of convolutional neural network in keras?
  • MatLab - Applying a function to each row in a matrix
  • Webpack use UglifyJSPlugin to ONLY remove comments
  • SQL query comparing an attribute in multiple tuples based on values of another attribute within the
  • Why doesn't explicit COLLATE override database collation?
  • VHDL - iSIM output uninitialised, doesn't change states
  • Log Write Output to File in CAPL [closed]
  • What is the real purpose of magic method __set_state in PHP?
  • Converting RVML to SVG using XSLT in C#
  • QSystemTrayIcon and Windows8
  • Calling java project from Mathematica
  • PHP file_exists() anomaly
  • Visualizing a large matrix in matlab
  • Change attribute of custom directive
  • Haskell: function composition with anonymous/lambda function
  • Insertion large number of Entities into SQL Server 2012 [duplicate]
  • What does certain JVM do after loading ByteCode into memory?
  • Should a web service response include empty values?
  • Creating a Multidimensional, Associative Array in VBScript
  • Add reference to ASP.NET 5 Class Library from Framework 4.5 Class Library Project
  • Implicit joins and Where in Doctrine - how?
  • Web.config system.webserver errors
  • print() is showing quotation marks in results
  • Highlight one bar in a series in highcharts?
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Calling of Constructors in a Java
  • 0x202A in filename: Why?
  • Traverse Array and Display in markup
  • Transpose CSV data with awk (pivot transformation)
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?
  • File not found error Google Drive API