An Introduction to Python Dictionary and Structuring Data

An Introduction to Python Dictionary and Structuring Data

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_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_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.

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.

# 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.

# 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.

# accessing with get() method
# output: None
print(python_dict.get(“experience”))
# 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_dict[“headline”]= “FrontEnd Developer”
# 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.

# 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.

# 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.

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

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

# 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.
# 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.
# output : [‘sachin’ , ‘Software Engineer’, ‘Sachin-chaurasiya’]
print(python_dict.values())
  • items() method Return sequence of dictionary items in (key , value) format.
# 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 | Twitter

Did you find this article valuable?

Support Sachin Chaurasiya by becoming a sponsor. Any amount is appreciated!