Python dictionary and structuring data
Tags: python, programming, webdev
Published: 2021-12-11 10:00:18

In This article, I will discuss dictionary data type which provides a flexible way to access and organize data. Also, I will discuss how they are created, how to access, remove, add elements from them.

> This article defines what is dictionary data type and how to perform some operations with them.
We will also learn how to use various built-in methods in dictionaries.

## What is a dictionary in python?

A dictionary is a mutable (Changeable), unordered collection of many values. indexes for dictionaries can use different data types, not just integer. Indexes for dictionaries are called keys, and a key with its associated value is called a key-value pair.

## Creating python dictionary

Creating a dictionary is very simple you have to just place the key and value inside curly braces {}.

One key: value pair is known as dictionary item. Here key should be unique and of immutable (unchangeable) type like a number, string and tuple, value could be of any type and can repeat.

For example:

```python
python_dict={“name”: “sachin”, “headline”: “Software Engineer”, “github_username”: “Sachin-chaurasiya”}
```

So the above code will create a dictionary named python_dict with keys **name, headline and  github_username** and the value for these keys are **sachin, Software Engineer and Sachin-chaurasiya** respectively.

Some more examples of how you can create a dictionary.

Python has a built-in method called dict() to create a dictionary.

```python
python_dict=dict({“name”: “sachin”, “headline”: “Software Engineer”, “github_username”: “Sachin-chaurasiya”}).
```

You can create a dictionary from a sequence having each item as a pair.

```python
sequence=[(“name”, “sachin”),(“headline” , “Software Engineer”), (“github_username”, “Sachin-chaurasiya”)]

python_dict=dict(sequence).
```

## Accessing Element from a dictionary

As I mentioned earlier to access elements from a dictionary you will need to know the key.

So let’s say we want to access the name from the python_dict dictionary.
The code will look like this to get a name from the dictionary.

```python
# it will return the value of the key “name” that is “sachin”.
name=python_dict[“name”] 
```
 

We can also access the value from a dictionary using the built-in get method.

```python
# output  sachin
name=python_dict.get(“name”)
```

What if we try to access the keys which do not exist in the dictionary? Let’s try it out.

```python
# accessing with get() method
# output: None
print(python_dict.get(“experience”))
```


```python
# accessig with []
# output: KeyError
print(python_dict[“experience”])
```

So in the case of the square bracket, we will get KeyError and in the case of get() method, we will get None.

If we are using a square bracket then we have to manually handle the error but in the case of get(), it’s already handled so always try to use the get() method while accessing dictionary elements.

## Updating dictionary elements

As we discussed dictionaries are mutable which means we can change the dictionary elements. so let’s see with some examples.

To update the element of the dictionary we should know the key of the element that we are going to update.

We can update the dictionary element using the assignment operator. So let’s say we want to update the value of “headline”

```python
python_dict[“headline”]= “FrontEnd Developer”
```

```python
# output : {“name”: “sachin”, “headline”: “FrontEnd Developer”, “github_username”: “Sachin-chaurasiya”}
print(python_dict)
```

What if we try to update the dictionary using keys which does not exist in the dictionary? So in this case the new element is get added to the dictionary with the key: value pair.

## Removing elements from the dictionary

There are various ways we can use to remove elements from a dictionary.

Using pop() method
Using del keyword
Using popitem() method
Using clear() method

So let’s see them all one by one.

If we want to remove an element from the dictionary but also get its corresponding value then we should use the pop() method.

```python
# output : sachin
print(python_dict.pop(“name”))
```

If we want to remove an element and get the whole element as a return value that is (key : value ) pair then we should use the popitem() method.

```python
# output : (“github_username”, “Sachin-chaurasiya”)
print(python_dict.popitem())
```

Let say we want to remove all the elements from the dictionary then we should use the clear() method.

```python
# output : {}
print(python_dict.clear())
```

To delete the dictionary itself we should use the del keyword.
 del python_dict

```python
# this will throw an error
print(python_dict)
```

## Three most powerful built-in methods of a python dictionary.
 
The **keys(), values() and items()** methods.

- **Keys() method**
Let say we want to print all the keys of a dictionary as a list then we should use this powerful keys() method.

```python
# output : [‘name’, ‘headline’ ,’github_username’]
print(python_dict.keys())
```

- **values() method**
Similar to the keys() method but it will return all the values of the dictionary as a list.

```python
# output : [‘sachin’ , ‘Software Engineer’, ‘Sachin-chaurasiya’]
print(python_dict.values())
```

- **items() method**
Return sequence of dictionary items in (key , value) format.

```python
# output : [(“name”, “sachin”),(“headline” , “Software Engineer”), (“github_username”, “Sachin-chaurasiya”)]
print(python_dict.items())
```

## Summary

A dictionary is a mutable (Changeable), unordered collection of many values.
Dictionary can be used in places where you want to store data as key, value pair.
Dictionary has some powerful built-in methods which make the developer life easier.

And that’s it for this topic. Thank you for reading.

### Connect with me
[LinkedIn](https://www.linkedin.com/in/sachin-chaurasiya) | [Twitter](https://twitter.com/sachindotcom)

<a href="https://www.buymeacoffee.com/sachin87" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>