Python dict ()

Il costruttore dict () crea un dizionario in Python.

Diverse forme di dict()costruttori sono:

 class dict (** kwarg) class dict (mapping, ** kwarg) class dict (iterabile, ** kwarg)

Nota: **kwarg consente di prendere un numero arbitrario di argomenti di parole chiave.

Un argomento parola chiave è un argomento preceduto da un identificatore (ad es. name=). Quindi, l'argomento della parola chiave del modulo kwarg=valueviene passato al dict()costruttore per creare dizionari.

dict()non restituisce alcun valore (restituisce None).

Esempio 1: creare un dizionario utilizzando solo argomenti di parole chiave

 numbers = dict(x=5, y=0) print('numbers =', numbers) print(type(numbers)) empty = dict() print('empty =', empty) print(type(empty))

Produzione

 numeri = ('y': 0, 'x': 5) vuoto = () 

Esempio 2: creare un dizionario utilizzando Iterable

 # keyword argument is not passed numbers1 = dict((('x', 5), ('y', -5))) print('numbers1 =',numbers1) # keyword argument is also passed numbers2 = dict((('x', 5), ('y', -5)), z=8) print('numbers2 =',numbers2) # zip() creates an iterable in Python 3 numbers3 = dict(dict(zip(('x', 'y', 'z'), (1, 2, 3)))) print('numbers3 =',numbers3)

Produzione

 numeri1 = ('y': -5, 'x': 5) numeri2 = ('z': 8, 'y': -5, 'x': 5) numeri3 = ('z': 3, 'y' : 2, 'x': 1)

Esempio 3: creare un dizionario utilizzando la mappatura

 numbers1 = dict(('x': 4, 'y': 5)) print('numbers1 =',numbers1) # you don't need to use dict() in above code numbers2 = ('x': 4, 'y': 5) print('numbers2 =',numbers2) # keyword argument is also passed numbers3 = dict(('x': 4, 'y': 5), z=8) print('numbers3 =',numbers3)

Produzione

 numeri1 = ('x': 4, 'y': 5) numeri2 = ('x': 4, 'y': 5) numeri3 = ('x': 4, 'z': 8, 'y': 5 )

Letture consigliate: dizionario Python e come lavorarci.

Articoli interessanti...