Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will dict(**kwargs) always give dictionary where Keys are of type string?

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 :

  1. Method-2 is the dict(**kwargs) way of creating a dictionary.
  2. In 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.

like image 705
Somjit Avatar asked Oct 26 '15 05:10

Somjit


1 Answers

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}
like image 80
thefourtheye Avatar answered Oct 09 '22 06:10

thefourtheye