Accessing elements

Unlike elements in a list, those in a dictionary are not ordered and cannot be accessed by their position index numbers. Instead, they are identified by their keys: dict[key]. For example:

fruits = {'apple': 3, 'pear': 2, 'orange': 10}

print(fruits['pear'])         # 2

Assign value to a key

Similar to lists, dictionaries are mutable, which means we can add, change or remove key:value pairs.

Assignment:

dict[key] = value

The assignment adds a new element to the dictionary if the key did not already exist, or replaces the old value with the new value if the key already exists.

print(fruits)       # {'apple': 3, 'pear': 2, 'orange': 10} (the order may be different)

# assign new value
fruits['pear'] = 28
print(fruits['pear'])       # 28 (existing key's value changed)

# add new element
fruits['kiwi'] = 15
print(fruits)          # {'apple': 3, 'pear': 28, 'orange': 10, 'kiwi' : 15}

Delete a key:value pair

In order to delete a key, use the del keyword:

del fruits['kiwi']

results matching ""

    No results matching ""