Reputation: 2772
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.
Upvotes: 7
Views: 4301
Reputation: 239613
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}
Upvotes: 4
Reputation: 49330
Method 1, a literal dictionary expression, can use as keys any hashable value, like strings, integers, or tuple
s.
Method 2 - the dict()
built-in function - doesn't "know" that the keys are strings. Whatever keys you use with that method have to follow traditional variable naming conventions, to be converted into strings. That means that each key must start with a letter or underscore, contain only letters, underscores, or numbers, and so on. Trying a different key, like 2a
or (1,2)
, will fail.
Upvotes: 2