Will dict (** kwargs) always give a dictionary where Keys have a type string?

Note This is not a duplicate of the linked answer , which focuses on performance issues and what happens behind the curtains when the dict () function is called. My question is that keyword arguments always result 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. I like to say python to give me a dictionary where are the lines and is the number . But in method-2, how does python know that keys are strings, and not something else?

Is this a trend? if so, then some other examples (except dictionaries) that show this peculiar behavior?

EDIT-1 :

My understanding of the answers:

  • Method-2 is a way to create a dict(**kwargs) dictionary dict(**kwargs) .
  • In spades=3 , spades is a valid Python identifier, so it is taken as a string key.

So, will dict(**kwargs) always be the result in a dictionary where the keys are of type string ?

EDIT-2 : ^^ YES.

+5
source share
2 answers

In the second case, the dict function takes keyword arguments. And keyword arguments can only be passed as string parameters.

Quoting documentation ,

Providing keyword arguments, as in the first example, only works for keys that are valid Python identifiers. Otherwise, you can use any valid keys.

As long as the string is a valid python identifier, you can use it 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} 
+4
source

Method 1, a dictionary dictionary expression, can use any hashed value as keys, such as strings, integers, or tuple s as keys.

Method 2 - the built-in dict() function - does not know that the keys are strings. No matter which keys you use with this method, you must follow the traditional conventions for variable names that need to be converted to strings. This means that each key must begin with a letter or underscore, contain only letters, underscores or numbers, etc. An attempt to execute another key, for example 2a or (1,2) , will fail.

+2
source

Source: https://habr.com/ru/post/1234505/


All Articles