# Python Dictionaries

In our previous blog post, we delved into the [Python](https://www.nbshare.io/notebook/669278718/Dictionaries-In-Python/) tuple function. If you missed that article, I highly recommend checking it out before continuing with this one. In this blog post, we'll provide a brief overview and correction of the concepts covered in the previous post. We explored [Python](https://www.askpython.com/python/dictionary/python-dictionary-dict-tutorial) tuples, their syntax, usage, and common operations. Today, we'll delve deeper into advanced topics and use cases to effectively use [dictionaries](https://github.com/topics/python-dictionary) in [Python](https://www.hackerearth.com/practice/python/working-with-data/dictionary/tutorial/) programs.

<div data-node-type="callout">
<div data-node-type="callout-emoji">🔍</div>
<div data-node-type="callout-text"><a target="_blank" rel="noopener noreferrer nofollow" href="https://blog.bytescrum.com/essential-python-functions-unlocking-the-power-of-tuples" style="pointer-events: none">https://blog.bytescrum.com/essential-python-functions-unlocking-the-power-of-tuples</a></div>
</div>

## Dictionaries

[Dictionaries](https://pythonbasics.org/dictionary/) are a basic data structure in [Python](https://www.analyticsvidhya.com/blog/2021/06/working-with-lists-dictionaries-in-python/) that is used to store and manage data collections. In other programming languages, they are known as associative arrays or hash maps. [Dictionaries](https://www.codecademy.com/resources/docs/python/dictionaries) in [Python](https://www.digitalvidya.com/blog/python-dictionary/) are unordered collections of [key-value pairs](https://www.educba.com/python-dictionary-keys/), with each key being unique.

### Creating a [Dictionary](https://learnpython.com/blog/create-dictionary-in-python/)

A [dictionary](https://python-reference.readthedocs.io/en/latest/docs/dict/) is created by enclosing a sequence of [key-value pairs](https://www.datacamp.com/tutorial/python-dictionaries) within curly braces, which can be of various data types.

```python
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
```

### Accessing Values

The values in a [dictionary](https://www.knowledgehut.com/tutorials/python-tutorial/python-dictionary) may be accessed by supplying the [key](https://appdividend.com/2022/07/12/python-dictionary-keys/) wrapped in square brackets or by using the **'get()'** function. If the [key](https://pythonexamples.org/python-dictionary-keys-to-list/) does not exist, it is better to use **'get()'** with a default value.

```python
name = my_dict['name']  # Accessing 'Alice' using the key 'name'
age = my_dict.get('age', 0)  # Accessing '30' using get() with a default value
```

### Modifying a [Dictionary](https://www.mygreatlearning.com/blog/dictionary-python/)

A [dictionary](https://medium.com/analytics-vidhya/an-introduction-to-python-dictionary-520302924ef8)'s [key-value pairs](https://blog.finxter.com/python-dict-keys-method/) can be added, modified, or removed.

```python
my_dict['occupation'] = 'Engineer'  # Adding a new key-value pair
my_dict['age'] = 30  # Modifying the value for an existing key
del my_dict['city']  # Removing a key-value pair
```

### [Dictionary](https://www.guvi.in/zen-class/python-course/?utm_source=Google&utm_medium=Search&utm_campaign=Mini-Course-Python-Feb-22&utm_network=g&utm_device=c&utm_keyword=python&gad=1&gclid=CjwKCAjwgsqoBhBNEiwAwe5w0_2ywld-KtPWyWdIcqhonurH5bekiZCvyh3fh-iRPOJMN29uEMoB5RoCsXIQAvD_BwE) Methods

[Dictionaries](https://www.edureka.co/blog/dictionary-in-python/) have a variety of built-in ways of performing common tasks.

* `keys()`: Returns a view of all [keys](https://logicmojo.com/python-dictionary).
    
* `values()`: Returns a view of all values.
    
* `items()`: Returns a view of all [key-value](https://garhara.kvs.ac.in/sites/defaul) pairs as [tuples](https://openbookproject.net/thinkcs/python/english3e/dictionaries.html).
    
* `get(key, default)`: Returns the value for the given [key](https://www.learntek.org/blog/python-dictionary/), or a default value if the [key](https://studymachinelearning.com/python-dictionary/) is not found.
    
* `pop(key, default)`: Removes and returns the value associated with the [key](https://pythonprogramminglanguage.com/dictionary/), or a default value if the [key](https://www.techbeamers.com/python-dictionary/) is not found.
    
* `update(dict2)`: Updates the [dictionary](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html) with [key-value](https://www.pythoncheatsheet.org/cheatsheet/dictionaries) pairs from another [dictionary](http://introtopython.org/dictionaries.html).
    
* `clear()`: Removes all [key-value](https://betterdatascience.com/python-dictionaries/) pairs from the [dictionary](https://blog.hubspot.com/website/python-dictionary).
    

### `keys()`: Returns a view of all keys.

This method returns a [list](https://stackoverflow.com/questions/8953627/python-dictionary-keys-error) of all [keys](https://www.linode.com/docs/guides/python-3-dictionaries/) in the [dictionary](https://towardsdatascience.com/python-dictionaries-651acb069f94). If necessary, this view may be used to cycle through the [keys](https://log2base2.com/courses/python?utm_src=search&utm_target=spyDS&gclid=CjwKCAjwgsqoBhBNEiwAwe5w04N78afJC3f8XjXTjmD69amkEqNBvJ5J_LITNgATwWZC3jXAAyaSExoCGZMQAvD_BwE) or convert them to a list or another data structure.

```python
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
key_view = my_dict.keys()

# Iterating through keys
for key in key_view:
    print(key)

# Converting keys to a list
key_list = list(key_view)
print(key_list)
```

### `values()`: Returns a view of all values.

This method returns a [list](http://www.compciv.org/guides/python/fundamentals/dictionaries-overview/) of all the values in the [dictionary](https://python.land/python-data-types/dictionaries). This view, like '[**keys**](https://www.w3schools.com/python/ref_dictionary_keys.asp)**()**', may be used for iteration or conversion to other data types.

```python
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
value_view = my_dict.values()

# Iterating through values
for value in value_view:
    print(value)

# Converting values to a list
value_list = list(value_view)
print(value_list)
```

### `items()`: Returns a view of all key-value pairs as tuples.

Returns a [tuple](https://www.educative.io/answers/how-to-get-minimum-value-keys-from-a-dictionary-in-python) representation of all [key-value pairs](https://www.geeksforgeeks.org/python-get-dictionary-keys-as-a-list/) in the [dictionary](https://www.learnbyexample.org/python-dictionary/). Because each [tuple](https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html) comprises a [key-value pair](https://www.geeksforgeeks.org/python-dictionary-keys-method/), it may be used to iterate through both [keys](https://www.programiz.com/python-programming/methods/dictionary/keys) and values at the same time.

```python
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
item_view = my_dict.items()

# Iterating through key-value pairs
for key, value in item_view:
    print(key, value)

# Converting items to a list of tuples
item_list = list(item_view)
print(item_list)
```

### `get(key, default)`: Returns the value for the given key, or a default value if the key is not found.

The method returns the value associated with a [key](https://www.scaler.com/topics/python-dictionary-keys/) if it exists in the [dictionary](https://www.learnpython.org/en/Dictionaries), or defaults to the provided value if it's not found.

```python
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}

# Using get() to safely retrieve values
count = my_dict.get('apple', 0)  # Returns 3
unknown_count = my_dict.get('grape', 0)  # Returns 0
```

### `pop(key, default)`: Removes and returns the value associated with the [key](https://www.tutorialspoint.com/python/dictionary_keys.htm), or a default value if the [key](https://www.javatpoint.com/python-dictionary-keys-method) is not found.

This method safely removes and retrieves values from a [dictionary](https://stackabuse.com/python-dictionary-tutorial/) by removing the [key-value pair](https://www.toppr.com/guides/python-guide/references/methods-and-functions/methods/dictionary/keys/pthon-dictionary-keys/) with the specified [key](https://www.digitalocean.com/community/tutorials/python-add-to-dictionary) and returning the associated value.

```python
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}

# Using pop() to remove and retrieve a value
count = my_dict.pop('apple', 0)  # Removes 'apple' key and returns 3
unknown_count = my_dict.pop('grape', 0)  # Returns 0 (default value since 'grape' is not in the dictionary)
```

### `update(dict2)`: Updates the [dictionary](https://www.w3resource.com/python-exercises/dictionary/) with key-value pairs from another [dictionary](https://www.tutorialsteacher.com/python/python-dictionary).

The function updates the calling [dictionary](https://www.youtube.com/watch?v=daefaLgNkw0&ab_channel=CoreySchafer) with [key-value pairs](https://www.tutorialsteacher.com/python/dict-keys) from **dict2**, updating existing [keys](https://sparkbyexamples.com/python/python-dictionary-keys-method-usage/) if they exist, or adding new ones if they don't.

```python
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
new_data = {'banana': 4, 'grape': 1}

# Using update() to merge dictionaries
my_dict.update(new_data)
print(my_dict)  # {'apple': 3, 'banana': 4, 'cherry': 5, 'grape': 1}
```

### `clear()`: Removes all [key-value pairs](https://sparkbyexamples.com/python/how-to-get-dictionary-keys-in-python/) from the [dictionary](https://www.guru99.com/python-dictionary-beginners-tutorial.html).

This method is used to reset or clear the contents of a [dictionary](https://www.freecodecamp.org/news/create-a-dictionary-in-python-python-dict-methods/) by removing all [key-value pairs](https://note.nkmk.me/en/python-dict-keys-values-items/).

```python
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}
my_dict.clear()
print(my_dict)  # {}
```

### Using Loop with [Dictionaries](https://www.datacamp.com/tutorial/dictionary-python)

To access [keys](https://careerkarma.com/blog/python-dictionary-keys/) or [key-value pairs](https://python-reference.readthedocs.io/en/latest/docs/dict/keys.html), you can use loops to iterate over a [dictionary](https://www.w3schools.com/python/python_dictionaries.asp).

```python
for key in my_dict:
    print(key, my_dict[key])

for key, value in my_dict.items():
    print(key, value)
```

```python
 my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

   for key in my_dict:
       print(key, my_dict[key])
```

### Sorting the Elements of a [Dictionary](https://www.geeksforgeeks.org/python-dictionary/) using Lambdas

In [Python](https://www.shiksha.com/online-courses/articles/python-dictionary/), [dictionaries](https://docs.python.org/3/tutorial/datastructures.html) are unsorted, but you may sort them based on [keys](https://medium.com/@GalarnykMichael/python-basics-10-dictionaries-and-dictionary-methods-4e9efa70f5b9) or [values](https://www.codecademy.com/learn/dscp-python-fundamentals/modules/dscp-python-dictionaries/cheatsheet) and save the results in a list. Here's how to use a lambda function to sort a dictionary by [keys](https://blog.devgenius.io/6-ways-you-can-get-keys-from-a-python-dictionary-9487c57a16bf).

```python
my_dict = {'b': 2, 'a': 1, 'c': 3}

sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[0])}
print(sorted_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}
```

### Checking for Key Existence

To see if a [key](https://www.sololearn.com/Discuss/1462669/what-is-a-key-in-python-dictionaries) exists in a [dictionary](https://realpython.com/python-dicts/), use the in operator.

```python
if 'name' in my_dict:
    print('Name:', my_dict['name'])
```

### [Dictionary](https://www.tutorialspoint.com/python/python_dictionary.htm) Comprehensions

[Dictionary](https://www.javatpoint.com/python-dictionary) comprehensions, which are identical to list comprehensions but generate [dictionaries](https://www.pythontutorial.net/python-basics/python-dictionary/), can be used to build [dictionaries](https://en.wikibooks.org/wiki/Python_Programming/Dictionaries).

```python
squares = {x: x*x for x in range(1, 6)}
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
```

### Ordered [Dictionaries](https://www.digitalocean.com/community/tutorials/understanding-dictionaries-in-python-3)

Regular [dictionaries](https://www.simplilearn.com/dictionary-in-python-article) are guaranteed to keep the order of insertion starting with [Python](https://sentry.io/answers/python-dictionary-add-keys/) 3.7. Collections can be used to create an explicitly **'OrderedDict'** ordered [dictionary](https://www.educba.com/dictionary-in-python/).

```python
from collections import OrderedDict

ordered_dict = OrderedDict([('b', 2), ('a', 1), ('c', 3)])
```

### Converting Lists into [Dictionary](https://www.scaler.com/topics/python/dictionary-in-python/)

Using the '**dict()**' constructor, you may turn a list of [tuples](https://www.tutlane.com/tutorial/python/python-dictionary) into a [dictionary](https://pynative.com/python-dictionaries/). Each [tuple](https://builtin.com/data-science/python-dictionary) must have two elements: one for the [key](https://flexiple.com/python/check-if-key-exists-in-dictionary-python) and one for the value.

```python
my_list = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(my_list)
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}
```

### Converting Strings into [Dictionary](https://builtin.com/data-science/python-dictionary)

The `eval()` function can convert a string representing a [dictionary](https://brainstation.io/learn/python/dictionary) into a [dictionary,](https://www.educative.io/answers/how-to-create-a-dictionary-in-python?utm_campaign=brand_educative&utm_source=google&utm_medium=ppc&utm_content=performance_max_india&eid=5082902844932096&utm_term=&utm_campaign=%5BNew%5D+Performance+Max&utm_source=adwords&utm_medium=ppc&hsa_acc=5451446008&hsa_cam=18931439518&hsa_grp=&hsa_ad=&hsa_src=x&hsa_tgt=&hsa_kw=&hsa_mt=&hsa_net=adwords&hsa_ver=3&gclid=CjwKCAjwgsqoBhBNEiwAwe5w03fPYMaob_8XPavqu6I8Trxuf0bYQG-PxfZ7IiWqhD8aPi4sq6w8vhoCNLAQAvD_BwE) but caution is advised as it can execute arbitrary code.

```python
my_str = "{'name': 'Alice', 'age': 30, 'city': 'New York'}"
my_dict = eval(my_str)
```

### Passing [Dictionaries](https://developers.google.com/edu/python/dict-files) to Functions

[Dictionaries](https://www.dataquest.io/blog/python-dictionaries/), like any other data type, can be passed as arguments to functions.

```python
def print_dict(some_dict):
    for key, value in some_dict.items():
     print(key, value)

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print_dict(my_dict)
```

### Ordered [Dictionaries](https://www.ionos.com/digitalguide/websites/web-development/python-dictionary/)

From Python 3.7, [dictionaries](https://www.educative.io/answers/how-does-the-dictionary-work-in-python) are guaranteed to be ordered, preserving the insertion order of elements. The `collections.OrderedDict` class can be used to create ordered [dictionaries](https://sparkbyexamples.com/python/python-dictionary-with-examples/).

```python
from collections import OrderedDict

ordered_dict = OrderedDict([('b', 2), ('a', 1), ('c', 3)])
print(ordered_dict)  # Output: OrderedDict([('b', 2), ('a', 1), ('c', 3)])
```

As of [Python](https://www.oreilly.com/library/view/high-performance-python/9781449361747/ch04.html) 3.7 and later, regular [dictionaries](https://note.nkmk.me/en/python-dict-create/) maintain order, so `OrderedDict` may not always be necessary unless the order is essential in specific use cases.

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent"><a target="_blank" rel="noopener noreferrer nofollow" href="https://towardsdatascience.com/everything-you-need-to-know-about-dictionaries-in-python-de57480ac101" style="pointer-events: none">Python</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://cs.stanford.edu/people/nick/py/python-dict.html" style="pointer-events: none">dictionaries </a>are powerful data structures that efficiently store and manage <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.freecodecamp.org/news/python-sort-dictionary-by-key/" style="pointer-events: none">key-value pairs</a>, offering built-in methods, comprehensions, and support for ordered <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python" style="pointer-events: none">dictionaries</a>, making them essential for <a target="_blank" rel="noopener noreferrer nofollow" href="https://stackabuse.com/python-how-to-add-keys-to-dictionary/" style="pointer-events: none">Python</a> programmers.</div></details>

Thank you for reading our blog. Our top priority is your success and satisfaction. We are ready to assist with any questions or additional help.

Warm regards,

[**Kamilla Preeti Samuel,**](https://www.linkedin.com/in/preeti-samuel-kamilla-5a247962/)

**Content Editor**

[**ByteScrum Technologies Private Limited!**](https://www.bytescrum.com/) 🙏
