Python dict() function

In this post, we will see about python dict constructor.
There are three types of constructor, you can use.

Please note that **kwarg denotes arbitary number of keyword arguments.


Return

dict using keyword arguments

Here is a simple example of keyword arguments.
For example:

d=dict(x=1,y=0,name='John') print(d)

Output:

{‘x’: 1, ‘y’: 0, ‘name’: ‘John’}

dict using mapping

Here is an example to illustrate how to create dict using mapping

d1=dict({'x': 1, 'y': 0, 'name': 'John'}) print('d1=',d1) d2=dict({'x': 1, 'y': 0},name='John') print('d2=',d2)

Output:

d1= {‘x’: 1, ‘y’: 0, ‘name’: ‘John’}
d2= {‘x’: 1, ‘y’: 0, ‘name’: ‘John’}

dict using iterable

Here is an example to illustrate how to create dict using iterable

d1=dict([('name', 'John'), ('x', 1), ('y', 3)]) print('d1=',d1) #You can pass keyword arguments too d2=dict([('x', 1), ('y', 3)],name='John') print('d2=',d2) d3=dict(zip(['name', 'y', 'x'], ['John', 3, 1])) print('d3=',d3)

Output:

d1= {‘name’: ‘John’, ‘x’: 1, ‘y’: 3}
d2= {‘x’: 1, ‘y’: 3, ‘name’: ‘John’}
d3= {‘name’: ‘John’, ‘y’: 3, ‘x’: 1}

That’s all about Python dict().

Leave a Reply

Your email address will not be published. Required fields are marked *