Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

Dictionaries

Get a Value

[!TIP]

  • get will return None when it cannot find a value for the provided key whereas the key as index approach will raise an exception in case it did not find it in the dictionary.
  • Key as index is faster than get method.
  • Sometimes we want our app to crash if the key was not present.
profile = {
    "username": "Genghis_khan"
}
print(profile["age"])  # raises an exception
print(profile.get("age"))  # returns None

Delete a key-value Pair

[!TIP]

del performs better than pop.

in Operator – Membership Test Operator

[!NOTE]

The in operator in a sequence (e.g. an array) looks for that value’s presence in the sequence.

names = ["Mohammad", "Jawad"]
if "Alex" in names:
    print("Alex exists in the list")

Loop Over a Dictionary

[!TIP]

  • The items method is more readable.
  • The items method is more efficient.

Convert a List to Dictionary

Dictionary Comprehensions

numbers = {number: "even" if number % 2 == 0 else "odd"
           for number in range(1, 100)}
print(numbers)

setdefault Method

Instead of

account = {
    "credit": 123
}


def top_up(account):
    # TODO copy the object first
    if "credit" not in account:
        account["credit"] = 0

    account["credit"] += 10

    return account

You can do this:

# ...
account["credit"] = account.setdefault("credit", 0) + 10
return account

update Method

You can add key-value pairs of one dictionary to another by using this method:

user = { "name": "jawad" }
account = { "IBAN": "DE123456789012" }
user.update(account)

print(user)

Shallow Copy VS Deep Copy

[!TIP]

A simple deep copy helper function:

def simple_deepcopy(obj):
    res = {}

    for key, value in object.items():
        if value is Array:
            res[key] = value.copy()
            continue

        res[key] = value
    return res

fromkeys Method

YouTube/Aparat

Ref