Python dict ()

Konštruktor dict () vytvorí slovník v Pythone.

Rôzne formy dict()konštruktorov sú:

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

Poznámka: **kwarg Môžete si vziať ľubovoľný počet argumentov kľúčových slov.

Argument kľúčové slovo je argument, ktorému predchádza identifikátor (napr. name=). Preto je argument kľúčového slova vo formulári kwarg=valueodovzdaný dict()konštruktorovi na vytvorenie slovníkov.

dict()nevracia žiadnu hodnotu (vracia None).

Príklad 1: Vytvorenie slovníka iba pomocou argumentov kľúčových slov

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

Výkon

 čísla = ('y': 0, 'x': 5) prázdne = () 

Príklad 2: Vytvorenie slovníka pomocou 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)

Výkon

 numbers1 = ('y': -5, 'x': 5) numbers2 = ('z': 8, 'y': -5, 'x': 5) numbers3 = ('z': 3, 'y' : 2, „x“: 1)

Príklad 3: Vytvorenie slovníka pomocou mapovania

 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)

Výkon

 numbers1 = ('x': 4, 'y': 5) numbers2 = ('x': 4, 'y': 5) numbers3 = ('x': 4, 'z': 8, 'y': 5 )

Odporúčané čítanie: Slovník Pythonu a ako s nimi pracovať.

Zaujímavé články...