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

Python3 Dictionary

Python3 Dictionary

A dictionary is another mutable container model that can store objects of any type.

Each key=>value pair in a dictionary is separated by a colon :, pairs are separated by commas (,), and the whole dictionary is enclosed in braces {}, in the following format:


d = {key1 : value1, key2 : value2, key3 : value3 }

**Note:** dict is a Python keyword and built-in function, so it is not recommended as a variable name dict。

Keys must be unique, but values need not be.

Values can be of any data type, but keys must be immutable, such as strings and numbers.

A simple dictionary example:


tinydict = {'name': 'runoob', 'likes': 123, 'url': 'www.runoob.com'}

A dictionary can also be created like this:


tinydict1 = { 'abc': 456 }
tinydict2 = { 'abc': 123, 98.6: 37 }

Create an empty dictionary

Create an empty dictionary with braces { }:

Example

Create an empty dictionary with braces {}

emptyDict

=

{

}

 

Print the dictionary

print

(

emptyDict

)

 

Check the number of items in the dictionary

print

(

"Length:"

,

len

(

emptyDict

)

)

 

Check the type

print

(

type

(

emptyDict

)

)

The example above produces the following output:

{}
Length: 0

Create a dictionary with the built-in function dict():

Example

emptyDict

=

dict

(

)

 

Print the dictionary

print

(

emptyDict

)

 

Check the number of items in the dictionary

print

(

"Length:"

,

len

(

emptyDict

)

)

 

Check the type

print

(

type

(

emptyDict

)

)

The example above produces the following output:

{}
Length: 0


Access values in the dictionary

Put the corresponding key in square brackets, as in the following example:

Example

#!/usr/bin/python3

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

print

(

"

tinydict['Name']:

"

,

tinydict

[

'

Name

'

]

)

print

(

"

tinydict['Age']:

"

,

tinydict

[

'

Age

'

]

)

The example above produces the following output:


tinydict['Name']:  Runoob
tinydict['Age']:  7

If you access data with a key that is not in the dictionary, the following error is produced:

Example

#!/usr/bin/python3

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

print

(

"

tinydict['Alice']:

"

,

tinydict

[

'

Alice

'

]

)

The example above produces the following output:


Traceback (most recent call last):
  File "test.py", line 5, in 
    print ("tinydict['Alice']: ", tinydict['Alice'])
KeyError: 'Alice'

Modify a dictionary

To add new content to a dictionary, add a new key/value pair; modifying or deleting existing key/value pairs is shown below:

Example

#!/usr/bin/python3

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

tinydict

[

'

Age

'

]

=

8

Update Age

tinydict

[

'

School

'

]

=

"

Runoob Tutorial

"

Add information

print

(

"

tinydict['Age']:

"

,

tinydict

[

'

Age

'

]

)

print

(

"

tinydict['School']:

"

,

tinydict

[

'

School

'

]

)

The example above produces the following output:


tinydict['Age']:  8
tinydict['School']:  Runoob Tutorial

Delete dictionary elements

You can delete a single element or clear the dictionary; clearing takes only one operation.

To explicitly delete a dictionary, use the del command, as in the following example:

Example

#!/usr/bin/python3

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

del

tinydict

[

'

Name

'

]

Delete key 'Name'

tinydict

.

clear

(

)

Clear the dictionary

del

tinydict

Delete the dictionary

print

(

"

tinydict['Age']:

"

,

tinydict

[

'

Age

'

]

)

print

(

"

tinydict['School']:

"

,

tinydict

[

'

School

'

]

)

But this raises an exception, because after the del operation the dictionary no longer exists:


Traceback (most recent call last):
  File "/runoob-test/test.py", line 9, in 
    print ("tinydict['Age']: ", tinydict['Age'])
NameError: name 'tinydict' is not defined

**Note:** the del() method is also discussed later.

Characteristics of dictionary keys

Dictionary values can be any Python object, either standard or user-defined, but keys cannot.

Two important points to remember:

1) The same key may not appear twice. If a key is assigned twice during creation, the later value is remembered, as shown below:

Example

#!/usr/bin/python3

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

,

'

Name

'

:

'

Little Rookie

'

}

print

(

"

tinydict['Name']:

"

,

tinydict

[

'

Name

'

]

)

The example above produces the following output:


tinydict['Name']:  小菜鸟

2) Keys must be immutable, so numbers, strings, or tuples can be used, but lists cannot, as shown below:

Example

#!/usr/bin/python3

tinydict

= {

[

'

Name

'

]

:

'

Runoob

'

,

'

Age

'

:

7

}

print

(

"

tinydict['Name']:

"

,

tinydict

[

'

Name

'

]

)

The example above produces the following output:


Traceback (most recent call last):
  File "test.py", line 3, in 
    tinydict = {['Name']: 'Runoob', 'Age': 7}
TypeError: unhashable type: 'list'

Dictionary built-in functions and methods

Python dictionaries contain the following built-in functions:

No. Function and description Example
1 len(dict)
Counts the number of dictionary elements, i.e. the total number of keys.

   

>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> len(tinydict) 3 | | 2 | str(dict)
Outputs the dictionary as a printable string representation. |

>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> str(tinydict)
"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
| | 3 | type(variable)
Returns the type of the input variable; if the variable is a dictionary, returns the dictionary type. |
>>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> type(tinydict)

|

Python dictionaries contain the following built-in methods:

No. Function and description
1 dict.clear()
Remove all elements from the dictionary
2 dict.copy()
Return a shallow copy of a dictionary
3 dict.fromkeys()
Create a new dictionary using the elements of sequence seq as keys and val as the initial value for all keys
4 dict.get(key, default=None)
Return the value of the specified key; if the key is not in the dictionary, return the default value set by default
5 key in dict
Returns true if the key is in dict, otherwise false
6 dict.items()
Return a view object as a list
7 dict.keys()
Return a view object
8 dict.setdefault(key, default=None)
Similar to get(), but if the key is not in the dictionary, it adds the key and sets its value to default
9 dict.update(dict2)
Update dict with the key/value pairs from dict2
10 dict.values()
Return a view object
11 dict.pop(key[,default])
Remove the value corresponding to a dictionary key and return that value.
12 dict.popitem()
Return and remove the last key/value pair in the dictionary.