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.
解决方案
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'