Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python dict() Function

Python dict() Function

Python3 Built-in Functions Python3 built-in function


dict() is a built-in Python function that creates dictionaries.

A dictionary is a key-value data structure in Python, where each key maps to a value.dict() The function can create dictionaries in several ways.

Word meaning: dict Is dictionaryis short for (dictionary).


Basic syntax and parameters

Syntax format


dict()
dict(mapping)
dict(**kwargs)
dict(iterable, **kwargs)

Parameter Description

- Type: mapping object (such as a dictionary) - Description: create a new dictionary from a mapping object. - Type: keyword arguments - Description: create a dictionary using keyword arguments. - Type: iterable - Description: an iterable whose elements are key/value pairs.

Function description


Example

Example 1: creating dictionaries

Example

Empty dictionary

d

=

dict

(

)

print

(

d

)

 

Output: {}

Keyword arguments (most common)

d

=

dict

(

name

=

"Tom"

,

age

=

20

)

print

(

d

)

 

Output: {'name': 'Tom', 'age': 20}

Create from a mapping object

d1

=

{

"name"

:

"Tom"

}

d2

=

dict

(

d1

)

print

(

d2

)

 

Output: {'name': 'Tom'}

Create from an iterable (whose elements are key/value pairs)

pairs

=

[

(

"name"

,

"Tom"

)

,

(

"age"

,

20

)

]

d

=

dict

(

pairs

)

print

(

d

)

 

Output: {'name': 'Tom', 'age': 20}

Create from zip

keys

=

[

"name"

,

"age"

,

"city"

]

values

=

[

"Tom"

,

20

,

"Beijing"

]

d

=

dict

(

zip

(

keys

,

values

)

)

print

(

d

)

 

Output: {'name': 'Tom', 'age': 20, 'city': 'Beijing'}

Expected output:


{}
{'name': 'Tom', 'age': 20}
{'name': 'Tom'}
{'name': 'Tom', 'age': 20}
{'name': 'Tom', 'age': 20, 'city': 'Beijing'}

Code analysis:

  1. Keyword arguments are the most common way to create a dictionary.
  2. Elements of the iterable must be key/value pairs (tuple or list).
  3. dict(zip()) is a common trick for merging two lists into a dictionary.

Example 2: dictionary operations

Example

Access values

d

=

{

"name"

:

"Tom"

,

"age"

:

20

}

print

(

d

[

"name"

]

)

   

Output: Tom

print

(

d.

get

(

"age"

)

)

 

Output: 20

Add / modify

d

[

"city"

]

=

"Beijing"

d

[

"age"

]

=

21

print

(

d

)

 

Output: {'name': 'Tom', 'age': 21, 'city': 'Beijing'}

Delete

del

d

[

"age"

]

print

(

d

)

 

Output: {'name': 'Tom', 'city': 'Beijing'}

Iteration

for

key

,

value

in

d.

items

(

)

:

   

print

(

f

"{key}: {value}"

)

Expected output:

Tom
20
{'name': 'Tom', 'age': 21, 'city': 'Beijing'}
{'name': 'Tom', 'city': 'Beijing'}
name: Tom
city: Beijing

Dictionaries support rich operations: access, add, modify, delete, iterate, and so on.


Python3 Built-in Functions Python3 built-in function