Python Dictionary¶
In Python, a dictionary is a collection of key-value pairs, while a file is a named location on disk or in memory used to store data that can be accessed or modified.
A dictionary is similar to a list in that it is a collection of objects.
- Mutable
- Dynamic (grow & shrink)
- Nested (optionally)
Instead of elements being targed by zero based indexing like we do in a list, a dictionary uses keys.
Key:Value pairs are written within {}.
Looking up or setting a value in dictionary uses the [].
This would look up the value of the key
foo
This creates a dictionary from empty []
dict = []
dict ['a'] = 'alpha'
dict ['b'] = 'beta'
dict ['c'] = 'sigma'
print(dict) ## {'a':'alpha', 'b':'beta', 'c':'sigma'}
Del¶
The del
operator handles deletions.
```python var = 6 del var # var no more!
list = ['a', 'b', 'c', 'd'] del list[0] ## Delete first element del list[-2:] ## Delete last two elements print(list) ## ['b']
dict = {'a':1, 'b':2, 'c':3} del dict['b'] ## Delete 'b' entry print(dict) ## {'a':1, 'c':3} ```