Python: Dictionary

By Xah Lee. Date: . Last updated: .

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

Create Dictionary

{key1:val1, key2:val2, …}

# python 3

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

Get Key's Value

dict[key]

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

Add Entry

dict[key] = value

# python 3

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]

# python 3

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

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

Get All Keys

dict.keys()

# python 3

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()

# python 3

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

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

Check Key Exist

key in dict

# python 3

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

# check if a key exists

print("b" in hh)
# True

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”.

# python 3

# 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 List, Tuple, Dictionary

Python

Regex

Text Processing

Web

Misc