tags:

views:

105

answers:

7
def a(*x):
    print x

a({'q':'qqq'})
a(*{'q':'qqq'})#why only print key.

traceback:

({'q': 'qqq'},)
('q',)

thanks

+2  A: 

When you're calling a function, using an asterisk before a list or dict will pass it in as positional parameters.

For example:

>>> a(*('test', 'testing'))
('test', 'testing')

>>> a(*{'a': 'b', 'c': 'd'})
('a', 'c')
Brian McKenna
+5  A: 

That's how dictionaries get converted to sequences.

tuple(dictionary) = tuple(dictionary.keys())

for a similar reason

for x in dictionary:

assigns keys, not pairs, to x

Jimmy
You could say that `*x` treats it's argument `x` as a sequence - python's sequence types are `tuple` or `list`. `**` treats its argument as a mapping.
THC4k
+1  A: 
a(*{'q' : 'qqq'})

will try to expand your dict ({'q':'qqq'}) into an itemized list of arguments for the function.

Note that:

tuple({'q' : 'qqq'})

returns ('q',), which is exactly what you're seeing. When you coerce a dictionary to a list/tuple, you only get the list of keys.

Sapph
+2  A: 

Using * in front of an expression in a function call iterates over the value of the expression (your dict, in this case) and makes each item in the iteration another parameter to the function invocation. Iterating over a dict in Python yields the keys (for better or worse).

Laurence Gonsalves
+1  A: 

Iterating a dictionary will yield its keys.

d = {'a': 1, 'b': 2, 'c': 3 }

for x in d:
    print x  # prints a, b, c but not necessarily in that order

sorted(d): # Gives a, b, c in that order. No 1/2/3.

If you want to get both keys and values from a dictionary, you can use .items() or .iteritems()

sorted(d.items()) # [('a,' 1), ('b', 2), ('c', 3)]
Crast
+1  A: 

You are asking for a list of arguments, and then telling python to send a dict as a sequence of arguments. When a dict is converted to a sequence, it uses the keys.

I guess you are really looking for **, not *.

truppo
** is arguably worse, because it will give an error; it tries to evaluate the dict as a mapping of named arguments.
Sapph
A: 

Probably because that's what a dictionary returns when you do a standard iteration over it. It gets converted to a sequence containing it's keys. This example exhibits the same behaviour:

>>> for i in {"a": "1", "b": "2"}:
...     print i
...
a
b

To get what I assume you expect you would pass it as variable keyword arguments instead, like this:

>>> def a(**kwargs):
...     print kwargs
...
>>> a(**{"a": "1", "b": "2"})
{'a': '1', 'b': '2'}

Note that you are now basically back where you began and have gained nothing.

Skurmedel