def a(*x):
print x
a({'q':'qqq'})
a(*{'q':'qqq'})#why only print key.
traceback:
({'q': 'qqq'},)
('q',)
thanks
def a(*x):
print x
a({'q':'qqq'})
a(*{'q':'qqq'})#why only print key.
traceback:
({'q': 'qqq'},)
('q',)
thanks
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')
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
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.
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).
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)]
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 *.
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.