Note : This is not a duplicate of the linked answer, that focuses on issues related to performance, and what happens behind the curtains when a dict() function call is made. My Question is about keyword arguments always resulting in keys of type string
. Definitely not a duplicate.
Method-1 :
suit_values = {'spades':3, 'hearts':2, 'diamonds':1, 'clubs':0}
Method-2 :
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
Method-1 makes sense to me. It's like telling python to give me a dictionary where keys are strings and values are numerics. But in Method-2, how does python know that the keys are strings and not something else ?
Is this a trend? if so, some other examples (apart from dictionaries) that show this kinda behavior ?
EDIT-1 :
My understanding from the answers is :
dict(**kwargs)
way of creating a dictionary.spades=3
, spades
is a valid Python identifier, so it is taken as a key of type string
. So, will dict(**kwargs)
always result in a dictionary where the keys are of type string
?
EDIT-2 : ^^ YES.
In the second case, the dict
function accepts keyword arguments. And the keyword arguments can only be passed as string parameters.
Quoting the documentation,
Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
As long as the string is a valid python identifier, you can used that as a key in the second form. For example, the following will not work with the second form
>>> dict(1=2)
File "<input>", line 1
SyntaxError: keyword can't be an expression
But the same will work with the first form
>>> {1:2}
{1: 2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With