Python dict() Function

Python 内置函数Python Built-in Functions


Description

dict()The 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 mapping relationships between objects.
  • iterable -- an iterable object.

Return Value

Return 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 a dictionary using the mapping function method {'three': 3, 'two': 2, 'one': 1} >>> dict([('one', 1), ('two', 2), ('three', 3)]) # Construct a dictionary using the iterable object method {'three': 3, 'two': 2, 'one': 1} >>>

Create a dictionary using only keyword arguments

Examples

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 examples is:

numbers = {'y': 0, 'x': 5}
<class 'dict'>
empty = {}
<class 'dict'>

Create a dictionary using an iterable object

Examples

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

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

# Use zip() to create an iterable object
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3)

The output of the above examples is:

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

Create a dictionary using a mapping

Mapping types are an associative container type that stores mapping relationships between objects.

Examples

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 examples is:

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

Python 内置函数Python Built-in Functions

Other Extensions