Python: Dictionary

By Xah Lee. Date: . Last updated: .

A python “dictionary” is a ordered list of pairs, each is a key and a value. (It also known as “keyed list”, “associative array”, “hash table”, in other languages.)

Before Python 3.7 (May 2018), dictionary is unordered.

Create Dictionary

{key1:val1, key2:val2, etc}

hh = {"john":3, "mary":4, "joe":5}
print(hh)
# {'joe': 5, 'john': 3, 'mary': 4}

Add a Entry

dict[key] = value

hh = {"john":3, "mary":4}

# add a entry
hh["vicky"] = 99
print(hh)
# {'john': 3, 'mary': 4, 'vicky': 99}

Delete a Entry

del dict[key]

hh = {"a":3, "b":4, "c":5}

# delete a entry
del hh["b"]
print(hh)
# {'a': 3, 'c': 5}

Check Key Exist

key in dict

hh = {"a":3, "b":4, "c":5}
# check if a key exists
print("b" in hh)
# True

Get Key's Value

dict[key]

hh = {"john":3, "mary":4, "joe":5}
print(hh["mary"])
# 4

Get Count

hh = {"a":3, "b":4, "c":5}
print(len(hh) )

Get All Keys

dict.keys()

hh = {"a":3, "b":4, "c":5}

print(hh.keys())
# dict_keys(['a', 'b', 'c'])

print(list(hh.keys()))
# ['a', 'b', 'c']

Get All Values

dict.values()

hh = {"a":3, "b":4, "c":5}

# get all values
print(hh.values())
# dict_values([3, 4, 5])

What Type Can be Used as Key in Dictionary?

A key in dictionary can be anything that's hashable. Basically, string, tuple, number, or in general python data types that are “immutable”.

# dict key can be anything that's hashable. typically, number, string, tuple. Most things that are “immutable”
hh = {2:3, "b":4, (3,4):5}

print(2 in hh)
# True

print((3,4) in hh)
# True

~2012 Thanks to 孙翰菲 for a tip.

Python Data Structure