Easy Tutorial
❮ Python Basic Operators Python Sum List ❯

Python dict() Function

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 explanations:

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 keyword arguments
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # Construct dictionary using a mapping function
{'three': 3, 'two': 2, 'one': 1} 
>>> dict([('one', 1), ('two', 2), ('three', 3)])    # Construct dictionary using an iterable object
{'three': 3, 'two': 2, 'one': 1}
>>>

Creating a Dictionary Using 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}
<class 'dict'>
empty = {}
<class 'dict'>

Creating a Dictionary Using an Iterable Object

Example

# Without keyword arguments
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =', numbers1)

# With keyword arguments
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =', numbers2)

# Using zip() to create an 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}

Creating a Dictionary Using Mapping

Mapping types are associative container types that store mappings between objects.

Example

numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =', numbers1)

# The following code does not need dict()
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =', numbers2)

# Keyword arguments are 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}

Python Built-in Functions

❮ Python Basic Operators Python Sum List ❯