Use dictionaries in Python

Business Benefits

Store key-value pairs that you can call without knowing the index location.


Create pairs of keys and values to store objects as dictionary elements using the syntax dict = {'key1':'value1','key2':'value2'}.

Dictionary elements consist of two parts: a key and a value. Use curly braces {} around the set of key-value pairs, a comma and space , to separate key-value pairs, and a colon : to separate each key from its paired value. For example, to create a contacts dictionary listing Tom, Jin, Ron, Jake, and their phone numbers:

>>> contacts = {
...     "tom": "122-444-333",
...     "jim": "412-1231-121",
...     "ron": "8912-121-1212",
...     "jake": "333-1881-121"
... }
## Output the contacts
>>>
>>> contacts
{'jim': '412-1231-121', 'jake': '333-1881-121', 'tom': '122-444-333', 'ron': '89
12-121-1212'}
>>>

Access the values in a dictionary using the syntax dict_name[key].

For example, if you wanted to obtain the phone number for Ron or Tom from the contacts dictionary created earlier:

>>> contacts = {
...     "tom": "122-444-333",
...     "jim": "412-1231-121",
...     "ron": "8912-121-1212",
...     "jake": "333-1881-121"
... }
>>>
## Show Ron's phone number
>>> contacts['ron']
'8912-121-1212'
>>>
## Show Tom's phone number
>>> contacts['tom']
'122-444-333'
>>>

Add or modify values within the dictionary using the syntax dict_name[key] = value.

Taking the above contacts dictionary example, to add a new element jane:

>>>
>>> contacts['jane'] = '443-123-991'  # adding new element
>>>
>>> contacts
{
    'jim': '412-1231-121',
    'jake': '333-1881-121',
    'tom': '122-444-333',
    'jane': '443-123-991',
    'ron': '8912-121-1212'
}
>>>
```If the key already exists in the dictionary, then its value will be updated:

contacts[‘jane’] = ‘443-123-000’ # update Jane’s number

contacts[‘jane’]
‘443-123-000’

## Delete values in a dictionary using a `del` statement with the syntax `del dict_name[key]`.

For example, `del contacts['ron']` would delete `ron` from your `contacts` dictionary:

del contacts[‘ron’]

contacts
{
‘jim’: ‘412-1231-121’,
‘jake’: ‘333-1881-121’,
‘tom’: ‘122-444-333’,
‘jane’: ‘443-123-000’
}

## Find out how many keys a dictionary contains using the built-in `len()` function.

For example, to obtain the length of your `contacts` dictionary, you would use `len(contacts)`:

len(contacts)
4

contacts
{
‘jim’: ‘412-1231-121’,
‘jake’: ‘333-1881-121’,
‘tom’: ‘122-444-333’,
‘jane’: ‘443-123-000’
}

## Iterate through elements in your dictionary and print specific values using a `for` loop.

For example, to print out the name of every key with a space between each:

for key in contacts:
… print(key, end=" ")

jim jake tom jane >>>

```Print a key’s value instead of its name by using the dictionary[key] syntax. For example:

>>>
>>> for key in contacts:
...   print(key, ":" , contacts[key])
...
jim : 412-1231-121
jake : 333-1881-121
tom : 122-444-333
jane : 443-123-000
>>>

Test the existence of a key inside a dictionary using in and not membership operators.

For example, to check whether jane and ron exist in the contacts dictionary:

>>>
>>> "jane" in contacts     # Does 'jane' exist in contacts?
True
>>>
>>> "ron" in contacts      # Does 'ron' exist in contacts?
False
>>>
```To check if `tom` *doesn't* exist:

“tom” not in contacts # Does ‘tom’ not exist in contacts?
False

## Test whether two dictionaries contain the same elements using comparison operators `==` or `!=`.

`==` checks whether both dictionaries contain the same elements, while `!=` checks whether the dictionaries do not contain the same elements. In the example below:

- `marks1 == marks2` tests whether the dictionary `marks1` contains the same elements as `marks2`, returning a value of `True`.
- `marks1 != marks2` checks whether the two dictionaries contain different elements, which returns a value of `False`:

marks1 = { ‘larry’: 90, ‘bill’: 60}
marks2 = { ‘bill’: 60, ‘larry’: 90}

marks1 == marks2
True

marks1 != marks2
False

## Use other common methods, such as `keys()`, `values()`, `items()`, `get()`, `pop()`, `popitem()`, `copy()`, and `clear()` to obtain key values as a sequence or tuple, or copy or remove key elements.

A few common methods that can call on a dictionary object are:

- Return a sequence containing only the keys from a dictionary using `keys()`:

contacts.keys()
dict_keys([‘jim’, ‘jane’, ‘tom’, ‘jake’])

type(contacts.keys())

```- Return a sequence containing only the values from the dictionary using values():

>>>
>>> contacts.values()
dict_values(['412-1231-121', '443-123-000', '122-444-333', '333-1881-121'])
>>>
>>> type(contacts.values())

>>>
>>> list(contacts.values())
['412-1231-121', '443-123-000', '122-444-333', '333-1881-121']
>>>
>>> tuple(contacts.values())
('412-1231-121', '443-123-000', '122-444-333', '333-1881-121')
>>>
```- Return a sequence of tuples, where each tuple contains a key and value of an element, using `items()`:

contacts.items()
dict_items([
(‘jim’, ‘412-1231-121’),
(‘jane’, ‘443-123-000’),
(‘tom’, ‘122-444-333’),
(‘jake’, ‘333-1881-121’)
])

type(contacts.items())

```- Return the value associated with a key using get(key,[default]). If the key is not found, None will be returned. Use an optional default value as the second argument to return the default value instead of None if the key cannot be found:

>>>
>>> print(contacts.get('jake'))
333-1881-121
>>>
>>> print(contacts.get('paul'))
None
>>>
>>> print(contacts.get('paul', "Not found"))
Not found
>>>
```- Return the value associated with the key and later remove the specified key and its corresponding value from the dictionary using `pop(key)`:

contacts
{
‘jim’: ‘412-1231-121’,
‘jane’: ‘443-123-000’,
‘tom’: ‘122-444-333’,
‘jake’: ‘333-1881-121’
}

contacts.pop(‘jim’)
‘412-1231-121’

contacts
{
‘jane’: ‘443-123-000’,
‘tom’: ‘122-444-333’,
‘jake’: ‘333-1881-121’
}

contacts.pop(‘jim’)
Traceback (most recent call last):
File “”, line 1, in
KeyError: ‘jim’

```- Remove and return a random element from the dictionary as a tuple using popitem():

>>> contacts.popitem()
('jane', '443-123-000')
>>>
>>> contacts
{'tom': '122-444-333', 'jake': '333-1881-121'}
>>>
```- Create a new copy of the dictionary using `copy()`:

contacts
{‘tom’: ‘122-444-333’, ‘jake’: ‘333-1881-121’}

id(contacts) # address of contacts dictionary
4131208

copy_contacts = contacts.copy() # create a copy of the contacts dictionary

copy_contacts
{‘jake’: ‘333-1881-121’, ‘tom’: ‘122-444-333’}

id(copy_contacts) # address of copy_contacts dictionary
4131272

```- Remove all elements from the dictionary using clear():

>>>
>>> contacts.clear()  # delete all the elements of a dictionary
>>>
>>> contacts
{}
>>>
>>> copy_contacts    # however, copy_contacts still contains a copy of the original dictionary object
{'jake': '333-1881-121', 'tom': '122-444-333'}
>>>

Last edited by @hesh_fekry 2023-11-14T11:07:36Z