Name

Dictionary

Examples
# Create a new dictionary
element_names = {'H': 'hydrogen', 'He': 'helium', 'Li': 'lithium'}

# Add another key/value pair to the dictionary
element_names['Be'] = 'beryllium'
element_names['B'] = 'boron'
element_names['C'] = 'carbon'

# Loop over elements of dictionary. Note that key/value pairs
# are returned in an arbitrary order!
for k, v in element_names.iteritems():
	print("symbol: " + k + "; name: " + v)

# Get an individual value by key
print(element_names['He']) # Prints 'helium'

# Delete an item from a dictionary
del element_names['C']

# Keys don't have to be strings! They can be of any (hashable)
# type. Values can also be of any type.
number_map = {
  1: [0.5, 1.0, 2.0],
  2: [10.0, 15.0, 20.0],
  3: [50.0, 75.0, 100.0]
}
print(number_map[2]) # Prints [10.0, 15.0, 20.0]

Description A dictionary is a Python data structure that stores a number of values, referenced by key. It's similar to a list, except values are accessed by keys of arbitrary types (usually strings), instead of with sequential integer indexes. Python's dictionary type is similar to "Maps" in Java, associative arrays in PHP, or hashes in Perl.

In Python, dictionary values can be of any type (and types can vary from one key/value pair to the next in the same dictionary). Keys can be of any type, as long as that type is "hashable" (see the Python glossary for more information).

Note that while Python remembers all key/value pairs added to a dictionary, it does not remember the order in which key/value pairs were added. As a consequence, when iterating over key/value pairs in a dictionary (with, e.g., the iteritems() method shown in the example above), the key/value pairs will come back in an arbitrary order, which may vary from one execution of your program to the next.

Syntax
d = {}
d = dict()
d = {key: value, key2: value}
Parameters
keyany immutable object; used to index the dictionary (ex. String or int)
valueany value to be stored in the dictionary
Methods
keys()Return a list of all keys in a dictionary.
items()Return a list of all key/value pairs in a dictionary (as tuples).
iteritems()Return an iterator, allowing easy and efficient means of iterating over a dictionary's key/value pairs.
values()Return a list of a dictionary's values.
update()Update a dictionary in place, adding or updating key/value pairs from a second dictionary.
Related {} (Curly braces)
[] (Index brackets)

Updated on Mon Sep 21 15:53:24 2020.

If you see any errors or have comments, please let us know.