Post

Python dict() Method

In this tutorial we will learn about the python dict() method and its uses.

Python dict() Method

The dict() method helps to create a Python dictionary.

Different forms of dict() constructors are:

1
2
3
dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)

Note: **kwarg let you take an arbitrary number of keyword arguments.

dict() Parameters

The dict() method has no parameters.

Let’s check some examples of dict() method.

Example 1: Creating a dictionary using dict() method.

1
2
3
numbers = dict(x=5,y=0)
print(numbers)
print(type(numbers))

Output as follow:

1
2
{'x': 5, 'y': 0}
<class 'dict'>

Example 2: Creating an Empty dictionary using the dict() method.

1
2
3
4
numbers = dict()
print(numbers)
print(type(numbers))

Output:

1
2
3
{}
<class 'dict'>

Example 3: Creating dictionary using Iterable

1
2
3
4
5
6
7
8
9
10
11
12
# 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)

The output will be as follow:

1
2
3
4
numbers1 = {'x': 5, 'y': -5}
numbers2 = {'x': 5, 'y': -5, 'z': 8}
numbers3 = {'x': 1, 'y': 2, 'z': 3}

###

Example 3: Create Dictionary Using Mapping

1
2
3
4
5
6
7
8
9
10
11
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)

When we run above from we will get the following result.

1
2
3
4
numbers1 = {'x': 4, 'y': 5}
numbers2 = {'x': 4, 'y': 5}
numbers3 = {'x': 4, 'z': 8, 'y': 5}

This post is licensed under CC BY 4.0 by the author.