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

Python Dictionary

Python Dictionary

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

Each key-value pair key:value in a dictionary is separated by a colon :, pairs are separated by commas ,, and the whole dictionary is enclosed in curly braces {}. The format is as follows:

d

= {

key1

:

value1

,

key2

:

value2

}

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

Keys are generally unique; if duplicated, the last key-value pair will replace the earlier one. Values do not need to be unique.

tinydict

=

{

'a'

:

1

,

'b'

:

2

,

'b'

:

'3'

}

tinydict

[

'b'

]

'3'

tinydict

{

'a'

:

1

,

'b'

:

'3'

}

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

A simple dictionary example:

tinydict

= {

'

Alice

'

:

'

2341

'

,

'

Beth

'

:

'

9102

'

,

'

Cecil

'

:

'

3258

'

}

A dictionary can also be created like this:

tinydict1

= {

'

abc

'

:

456

}

tinydict2

= {

'

abc

'

:

123

,

98.6

:

37

}


Access values in the dictionary

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

Example

#!/usr/bin/python

tinydict

= {

'

Name

'

:

'

Zara

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

print

"

tinydict['Name']:

"

,

tinydict

[

'

Name

'

]

print

"

tinydict['Age']:

"

,

tinydict

[

'

Age

'

]

The example above produces the following output:


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

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

Example

#!/usr/bin/python

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

print

"

tinydict['Alice']:

"

,

tinydict

[

'

Alice

'

]

The example above produces the following output:


tinydict['Alice']: 
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/python

-- coding: UTF-8 --

tinydict

= {

'

Name

'

:

'

Zara

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

tinydict

[

'

Age

'

]

=

8

update

tinydict

[

'

School

'

]

=

"

RUNOOB

"

add

print

"

tinydict['Age']:

"

,

tinydict

[

'

Age

'

]

print

"

tinydict['School']:

"

,

tinydict

[

'

School

'

]

The example above produces the following output:


tinydict['Age']:  8
tinydict['School']:  RUNOOB

Delete dictionary elements

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

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

Example

#!/usr/bin/python

-- coding: UTF-8 --

tinydict

= {

'

Name

'

:

'

Zara

'

,

'

Age

'

:

7

,

'

Class

'

:

'

First

'

}

del

tinydict

[

'

Name

'

]

Delete the entry whose key is 'Name'

tinydict

.

clear

(

)

Clear all entries in the dictionary

del

tinydict

Delete the dictionary

print

"

tinydict['Age']:

"

,

tinydict

[

'

Age

'

]

print

"

tinydict['School']:

"

,

tinydict

[

'

School

'

]

But this will raise an exception because after using del the dictionary no longer exists:


tinydict['Age']: 
Traceback (most recent call last):
  File "test.py", line 10, 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 unrestrictedly 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/python

tinydict

= {

'

Name

'

:

'

Runoob

'

,

'

Age

'

:

7

,

'

Name

'

:

'

Manni

'

}

print

"

tinydict['Name']:

"

,

tinydict

[

'

Name

'

]

The example above produces the following output:


tinydict['Name']:  Manni

2) Keys must be immutable, so numbers, strings, or tuples can be used, while lists cannot, as in the following example:

Example

#!/usr/bin/python

tinydict

= {

[

'

Name

'

]

:

'

Zara

'

,

'

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']: 'Zara', 'Age': 7} 
TypeError: unhashable type: 'list'

Dictionary built-in functions and methods

Python dictionaries contain the following built-in functions:

No. Function and description
1 cmp(dict1, dict2)
Compares two dictionary elements.
2 len(dict)
Counts the number of dictionary elements, i.e. the total number of keys.
3 str(dict)
Outputs a printable string representation of the dictionary.
4 type(variable)
Returns the type of the input variable; if the variable is a dictionary, it returns the dictionary type.

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(seq[, val])
Creates a new dictionary with elements from the sequence seq as keys and val as the initial value for all keys
4 dict.get(key, default=None)
Returns the value for the specified key, or the default value if the key is not in the dictionary
5 dict.has_key(key)
Returns true if the key is in the dictionary dict, otherwise false. Not supported in Python 3.
6 dict.items()
Returns an iterable list of (key, value) tuples
7 dict.keys()
Returns all keys of a dictionary as a list
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()
Returns all values in the dictionary as a list
11 pop(key[,default])
Removes the value corresponding to the given key in the dictionary and returns the removed value. The key must be provided; otherwise, the default value is returned.
12 popitem()
Return and remove the last key/value pair in the dictionary.