Python dict

  • Dictionaries are mutable unordered collections of key-value pairs
  • Keys within the dictionary must be unique and must be hashable.
  • That includes types like numbers, strings and tuples.
  • Lists and dicts can not be used as keys since they are mutable.
  • Dictionaries in other languages are also called hash tables or associative arrays.

create a dict

  • can use dict custructor to create dict
  • can create dict with syntax like {key1: value1, key2: value2}
  • can create empty dict with syntax {}
empty = {}
student = {
    "name": "Anji",
    "stream": "Computer Science",
    "grade": "A"
}
print(student)
# Output: {'name': 'Anji', 'stream': 'Computer Science', 'grade': 'A'}
nums = dict(one=1, two=2)
print(nums)
# Output: {'one': 1, 'two': 2}

add key to dict

  • use syntax dict[key] = value to add new key
car = {}
car["brand"] = "Ford"
car["model"] = "Mustang"
print(car)
# Output: {'brand': 'Ford', 'model': 'Mustang'}

access dict key

  • use syntax dict[key] to access key or use method dict.get(key)
  • dict[key] throws an error if key not found in dict.
  • dict.get(key) return None if key not found in dict.
car = {'brand': 'Ford', 'model': 'Mustang'}
print(car['brand'])
# Output: Ford

update dict key

  • use syntax dict[key] = new_value to update value
student = {"name": "John", "grade": "A"}
student["grade"] = "B"
print(student)
# Output: {'name': 'John', 'grade': 'B'}

delete dict key

  • use syntax del dict[key] key from dict
student = {"name": "John", "grade": "A"}
del student['grade']
print(student)
# Output: {'name': 'John'}

get dict keys

  • use method dict.keys() to get keys
address = {
    "line1": "4/23/10",
    "line2": "Golden street",
    "city": "London"
}
keys = address.keys()
print(keys)
# Output: dict_keys(['line1', 'line2', 'city'])

get dict values

  • use method dict.values() to get values
address = {
    "line1": "4/23/10",
    "line2": "Golden street",
    "city": "London"
}
values = address.values()
print(values)
# Output: dict_values(['4/23/10', 'Golden street', 'London'])

get dict items

  • use method dict.items() to get items
  • it will return data like [(key, value)]
address = {
    "line1": "4/23/10",
    "line2": "Golden street",
    "city": "London"
}
items = address.items()
print(items)
# Output: dict_items([('line1', '4/23/10'), ('line2', 'Golden street'), ('city', 'London')])

use for loop with dict

  • iterate through dict
product = {
    "name": "Ball",
    "cost": 100
}

for key in product:
    print(key, product[key])
# Output:
# name Ball
# cost 100
  • iterate through dict keys
product = {
    "name": "Ball",
    "cost": 100
}

for key in product.keys():
    print(key, product[key])
# Output:
# name Ball
# cost 100
  • iterate through dict values
product = {
    "name": "Ball",
    "cost": 100
}

for val in product.values():
    print(val)
# Output:
# Ball
# 100
  • iterate through dict items
product = {
    "name": "Ball",
    "cost": 100
}

for key, val in product.items():
    print(key, val)
# Output:
# name Ball
# cost 100

copying dict

  • copy dict to keep the original dict away from modifications.
  • use builtin constructor dict() or method dict.copy() to copy dict.
product = {
    "name": "Ball",
    "cost": 100
}

product_copy1 = product.copy()
product_copy1["name"] = "Pen"
print(product_copy1)
# Output: {'name': 'Pen', 'cost': 100}
print(product)
# Output: {'name': 'Ball', 'cost': 100}

product_copy2 = dict(product)
product_copy2["name"] = "Pencil"
print(product_copy2)
# Output: {'name': 'Pencil', 'cost': 100}
print(product)
# Output: {'name': 'Ball', 'cost': 100}

compare two dicts

  • use == operator to compare dicts
d1 = {"one": 1}
d2 = {"one": 1}
print(d1 == d2)
# Output: True

nested dicts

  • dict can have dicts as values
students = {
    "DT001": {
        "name": "John",
        "grade": "A"
    },
    "DT002": {
        "name": "Anji",
        "grade": "B"
    }
}

dict Methods

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

Read more about dict at python official docs

Rerefences