1

I'm confused with the statement " print(kw,":",keywords[kw])" in the following program, in python.

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)
    print(keywords)
    keys=sorted(keywords)
    print(keys)
    for kw in keys:
        print(kw,":",keywords[kw])


cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

The result is below:

--Do you have any Limburger ?
--I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
{'client': 'John Cleese', 'sketch': 'Cheese Shop Sketch', 'shopkeeper': 'Michael Palin'}
['client', 'shopkeeper', 'sketch']
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

In my idea, "kw" should be 'client', 'sketch' and 'shopkeeper', not numbers, then how can "kw" be the index of keywords in the statement " print(kw,":",keywords[kw])"?

To verify my idea, I also tried another program:

letters=['a','b']
for kw in letters:
   print(letters[kw])

And a reasonable reply pops up:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str

That furthermore confuses me for the problem I got in the first piece of program.I think it should pop up the same error to me.

Will
  • 4,585
  • 1
  • 26
  • 48

2 Answers2

0

It use the keywords utilities, it's a kind of array with a key name.

You can see the lib description, in the python documentation HERE

In fact there is a special properties of **keywords arguments that provides the right to do this.

HERE is a tutorial to use it (and also to understand it) and HERE is the stackoverflow related question.

Community
  • 1
  • 1
Yann
  • 318
  • 1
  • 14
0

Function arguments preceded with ** are called "keyword arguments", which take named parameters when calling the function, eg: client="John Cleese" in your example. In this case, "client" is the name and "John Cleese" is the value. Arguments passed this way are placed in a dict, which is a key-value store rather than a list, which you might be familiar with in the form

x = {
      "foo": "bar"
    } 
print x["foo"] # prints "bar"
minuteman3
  • 393
  • 1
  • 7