# Dictionaries

Dictionaries in Python are created using curly braces `{}` and consist of key-value pairs separated by colons `:`. They  are unordered collections of key-value pairs that allow for efficient lookup, insertion, and deletion of items based on their keys.  Each key in a dictionary must be unique and immutable, such as strings, numbers, or tuples. Keys are used to access corresponding values, which can be any data type, including lists, tuples, or even other dictionaries.&#x20;

Dataset:

```python
basketball_champions_top10= {
    'Los Angeles Lakers': 17,
    'Boston Celtics': 17,
    'Golden State Warriors': 7,
    'Chicago Bulls': 6,
    'San Antonio Spurs': 5,
    'Philadelphia 76ers': 3,
    'Detroit Pistons': 3,
    'Miami Heat': 3,
    'New York Knicks': 2,
    'Houston Rockets': 2,
    'Milwaukee Bucks': 2,
}
```

## 1. Accessing Dictionaries Elements <a href="#accessing-dictionaries-elements" id="accessing-dictionaries-elements"></a>

```python
# Print out the keys in basketball_champions
print(f"Keys: \n{basketball_champions_top10.keys()}\n")

# Print out the values in basketball_champions
print(f"Values: \n{basketball_champions_top10.values()}\n")

# Print out all key-value pairs with items()
print(f"Items: \n{basketball_champions_top10.items()}\n")

# Print out championship counts for 'Boston Celtics'
print(f"Boston Celtics championships: {basketball_champions_top10['Boston Celtics']}")


#OUTPUT
"""
Keys: 
dict_keys(['Los Angeles Lakers', 'Boston Celtics', 'Golden State Warriors', 'Chicago Bulls', 'San Antonio Spurs', 'Philadelphia 76ers', 'Detroit Pistons', 'Miami Heat', 'New York Knicks', 'Houston Rockets'])

Values: 
dict_values([17, 17, 7, 6, 5, 3, 3, 3, 2, 2])

Items: 
dict_items([('Los Angeles Lakers', 17), ('Boston Celtics', 17), ('Golden State Warriors', 7), ('Chicago Bulls', 6), ('San Antonio Spurs', 5), ('Philadelphia 76ers', 3), ('Detroit Pistons', 3), ('Miami Heat', 3), ('New York Knicks', 2), ('Houston Rockets', 2)])

Boston Celtics championships: 17
"""
```

{% hint style="info" %}
Unlike Python Lists , which are indexed by integers, Dictionaries are indexed by unique keys.
{% endhint %}

## 2. Updating Dictionaries

### 2.1. Adding new key-value pairs

```python
# unlike lists, dictionaries dict['new_key']=new_value syntax
# add 'Milwaukee Bucks' who has 2 championships
basketball_champions_top10 += {'Milwaukee Bucks': 2} # Error

#OUTPUT
"""
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[14], line 4
      1 # Adding new key-value pairs
      2 # unlike lists, dictionaries dict['new_key']=new_value syntax
      3 # add 'Milwaukee Bucks' who has 2 championships
----> 4 basketball_champions_top10 += {'Milwaukee Bucks': 2} # Error

TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'
"""


# correct way
basketball_champions_top10['Milwaukee Bucks']= 2
print(basketball_champions_top10)
print("---------------------")

# or using the method update()
basketball_champions_top10.update({'Cleveland Cavaliers': 1})
print(basketball_champions_top10)


#OUTPUT
"""
{'Los Angeles Lakers': 17, 'Boston Celtics': 17, 'Golden State Warriors': 7, 
'Chicago Bulls': 6, 'San Antonio Spurs': 5, 'Philadelphia 76ers': 3, 
'Detroit Pistons': 3, 'Miami Heat': 3, 'New York Knicks': 2, 'Houston Rockets': 2, 
'Milwaukee Bucks': 2}
---------------------
{'Los Angeles Lakers': 17, 'Boston Celtics': 17, 'Golden State Warriors': 7, 
'Chicago Bulls': 6, 'San Antonio Spurs': 5, 'Philadelphia 76ers': 3, 
'Detroit Pistons': 3, 'Miami Heat': 3, 'New York Knicks': 2, 'Houston Rockets': 2, 
'Milwaukee Bucks': 2, 'Cleveland Cavaliers': 1}
"""
```

### 2.2. Deleting new key-value pairs

```python
# delete 'Cleveland Cavaliers' and 'Milwaukee Bucks' and their values
# a. using del
del basketball_champions_top10['Cleveland Cavaliers']

# b. using .pop()
basketball_champions_top10.pop('Milwaukee Bucks')
print(basketball_champions_top10)

#OUTPUT
"""
{'Los Angeles Lakers': 17, 'Boston Celtics': 17, 'Golden State Warriors': 7, 
'Chicago Bulls': 6, 'San Antonio Spurs': 5, 'Philadelphia 76ers': 3, 
'Detroit Pistons': 3, 'Miami Heat': 3, 'New York Knicks': 2, 'Houston Rockets': 2}
"""
```

## 3. Dictionary Methods

<table><thead><tr><th width="137">Method</th><th>Description</th></tr></thead><tbody><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_clear.asp">clear()</a></td><td>Removes all the elements from the dictionary</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_copy.asp">copy()</a></td><td>Returns a copy of the dictionary</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_fromkeys.asp">fromkeys()</a></td><td>Returns a dictionary with the specified keys and value</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_get.asp">get()</a></td><td>Returns the value of the specified key</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_items.asp">items()</a></td><td>Returns a list containing a tuple for each key value pair</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_keys.asp">keys()</a></td><td>Returns a list containing the dictionary's keys</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_pop.asp">pop()</a></td><td>Removes the element with the specified key</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_popitem.asp">popitem()</a></td><td>Removes the last inserted key-value pair</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_setdefault.asp">setdefault()</a></td><td>Returns the value of the specified key. If the key does not exist: insert the key, with the specified value</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_update.asp">update()</a></td><td>Updates the dictionary with the specified key-value pairs</td></tr><tr><td><a href="https://www.w3schools.com/python/ref_dictionary_values.asp">values()</a></td><td>Returns a list of all the values in the dictionary</td></tr></tbody></table>

&#x20;                                        Click on the methods practice them on W3schools

```python
# get the value for a specific key
print(basketball_champions_top10.get('Boston Celtics'))
# remove the last item
print(basketball_champions_top10.popitem())

#OUTPUT
"""
17
('Houston Rockets', 2)
"""
```

## Conclusion

Dictionaries in Python are versatile data structures that store key-value pairs. Keys, which must be immutable and unique within a dictionary, are used to access associated values, which can be of any data type. Dictionaries provide a flexible way to organize and manipulate data, supporting operations like insertion, deletion, and modification of key-value pairs. They are commonly used to represent mappings/configurations and are fundamental in Python programming for their ability to provide efficient data organization and retrieval for various applications.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dshub.gitbook.io/ds-hub/python/basics/variables-and-datatypes/dictionaries.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
