Konstruktor dict () vytvoří slovník v Pythonu.
Různé formy dict()
konstruktorů jsou:
class dict (** kwarg) class dict (mapping, ** kwarg) class dict (iterable, ** kwarg)
Poznámka: **kwarg
umožní vám vzít libovolný počet argumentů klíčových slov.
Argument klíčové slovo je argument, kterému předchází identifikátor (např. name=
). Argument klíčového slova formuláře kwarg=value
je tedy předán dict()
konstruktoru k vytvoření slovníků.
dict()
nevrátí žádnou hodnotu (vrátí None
).
Příklad 1: Vytvořit slovník pouze pomocí argumentů klíčových slov
numbers = dict(x=5, y=0) print('numbers =', numbers) print(type(numbers)) empty = dict() print('empty =', empty) print(type(empty))
Výstup
numbers = ('y': 0, 'x': 5) empty = ()
Příklad 2: Vytvoření slovníku pomocí 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ýstup
numbers1 = ('y': -5, 'x': 5) numbers2 = ('z': 8, 'y': -5, 'x': 5) numbers3 = ('z': 3, 'y' : 2, 'x': 1)
Příklad 3: Vytvoření slovníku pomocí mapování
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ýstup
numbers1 = ('x': 4, 'y': 5) numbers2 = ('x': 4, 'y': 5) numbers3 = ('x': 4, 'z': 8, 'y': 5 )
Doporučené čtení: Slovník Pythonu a jak s nimi pracovat.