YouTip LogoYouTip

Python Func Dict

# Python2.x Python dict() Function [![Image 3: Python Built-in Functions](#) Python Built-in Functions](#) * * * ## Description The **dict()** function is used to create a dictionary. ## Syntax dict syntax: class dict(**kwarg)class dict(mapping, **kwarg)class dict(iterable, **kwarg) Parameter description: * **kwargs -- Keywords. * mapping -- A container of elements. Mapping types are an associative container type that stores the mapping relationship between objects. * iterable -- An iterable object. ## Return Value Returns a dictionary. ## Examples The following examples demonstrate the usage of dict: >>>dict()# Create an empty dictionary {} >>>dict(a='a', b='b', t='t')# Pass in keywords {'a': 'a', 'b': 'b', 't': 't'} >>>dict(zip(['one', 'two', 'three'], [1, 2, 3]))# Construct dictionary using mapping function {'three': 3, 'two': 2, 'one': 1} >>>dict([('one', 1), ('two', 2), ('three', 3)])# Construct dictionary using iterable object {'three': 3, 'two': 2, 'one': 1} >>> ### Create Dictionary Using Only Keyword Arguments ## Example numbers =dict(x=5, y=0) print('numbers =', numbers) print(type(numbers)) empty =dict() print('empty =', empty) print(type(empty)) The output of the above example is: numbers = {'y': 0, 'x': 5} empty = {} ### Create Dictionary Using Iterable Object ## Example # No keyword arguments set numbers1 =dict([('x',5),('y', -5)]) print('numbers1 =',numbers1) # Keyword arguments set numbers2 =dict([('x',5),('y', -5)], z=8) print('numbers2 =',numbers2) # zip() creates iterable object numbers3 =dict(dict(zip(['x','y','z'],[1,2,3]))) print('numbers3 =',numbers3) The output of the above example is: numbers1 = {'y': -5, 'x': 5} numbers2 = {'z': 8, 'y': -5, 'x': 5} numbers3 = {'z': 3, 'y': 2, 'x': 1} ### Create Dictionary Using Mapping Mapping types are an associative container type that stores the mapping relationship between objects. ## Example numbers1 =dict({'x': 4,'y': 5}) print('numbers1 =',numbers1) # The following code does not need to use dict() numbers2 ={'x': 4,'y': 5} print('numbers2 =',numbers2) # Keyword arguments will be passed numbers3 =dict({'x': 4,'y': 5}, z=8) print('numbers3 =',numbers3) The output of the above example is: numbers1 = {'x': 4, 'y': 5} numbers2 = {'x': 4, 'y': 5} numbers3 = {'x': 4, 'z': 8, 'y': 5} [![Image 4: Python Built-in Functions](#) Python Built-in Functions](#)
← Python Func SlicePython Func Help β†’