Dictionaries in Python

Jainharsh
Nerd For Tech
Published in
5 min readJul 11, 2021

Note:

Before getting started with this course, I recommend seeing the Learn Python For Beginners (Part-2) course

So Now Let’s Get Into It

Python Dictionaries and Its Functions

So What’s a dictionary in python? Let’s imagine a dictionary as a dictionary that we use in our everyday life where there is a word(key) and its meaning(value). So python dictionary is kinda same where we can store key-value pairs instead of storing a single element like in other data structures.
A dictionary is a mutable(can be changed) and an ordered data structure which is a pair of 2 values:
Key and Value.

Key

Keys are unique identifiers in python which are used to get an item from a dictionary in python. We cannot have 2 same keys in a dictionary. If you add keys representing different values, it will just overwrite the previous values. But you can create 2 same keys with different cases.

Value

In dictionary values, we can store strings, integers, lists, and even dictionaries (Nested Dictionary). Dictionary values can be the same, unlike keys.

Now let’s understand how to make a dictionary:

Creating a Dictionary

A dictionary can be created by created using curly braces (‘{}’) in which there key-value pairs.

Syntax

mydict = {key:value}

Now let’s create a dictionary:

Now let’s add a dictionary as a value in a dictionary(Nested Dictionary):

Here we make a variable ‘NestedDict’ which is a dictionary and It has a key ‘A’ and this key has a value of ‘B’ which is also a dictionary and holds further key-value pairs

Now Let’s Learn how to access its items now:

Accessing Dictionary Items

Now you might have probably guessed that to get the items of the dictionary, we use its key name(like we use the index in List) inside the square brackets([]). Now let’s access the above dictionary items.

Accessing Nested Dictionary Items

Accessing elements of a nested dictionary is almost the same as accessing items from a simple dictionary. Like we get items from a simple dictionary using square brackets(in which key is there), here we instead add one more pair of brackets(in which key of the nested dictionary is there ) to get the elements of the nested dictionary.

As you know, dictionaries are mutable(can be changed) so now let’s see how to add elements to a dictionary:

Adding Items to a Dictionary

We can easily add some items to a dictionary by putting square brackets (around the defined dictionary) in which a key name is added and of course followed by a value. An important point to note is if you add an element but if its key is already there in the dictionary its gets replaced(overwritten)

Syntax

MyDict["key"] = "Value"

Let’s add some elements to this dictionary in code:

Now how will you add items to a nested dictionary:

Adding a dictionary to nested a Dictionary

An important point to note here is that when adding items to a nested dictionary, a nested dictionary should be there in the dictionary unlike when we add items to the dictionary. The syntax to add elements to a nested dictionary is as follows:

mydict["AlreadyAddedKey"]["key"]=["value"]

We can add a dictionary to a nested dictionary by putting square brackets in which the already added key(in which we want to place this dictionary) is added which is followed by our custom key and value. I know you couldn’t understand it, so let’s see it in code

Now after this, let’s understand how can we remove items from the list

Removing items from the dictionary

Deleting items from the dictionary is quite simple and can be done in 2–3 ways:

  • Pop
    Removes the item with the specified key-value
myDict = {
"FirstName":"John",
"Grade":"1st",
"LastName":"abc"
}
myDict.pop("Grade")print(myDict) # {'FirstName': 'John', 'LastName': 'abc'} (No Grade key)
  • Del Keyword
    The del keyword is also used pop items with a specific value
myDict = {
"FirstName":"John",
"Grade":"1st",
"LastName":"abc"
}
del myDict["Grade"]print(myDict)

Removing items from Nested dictionary

Removing elements from a nested dictionary can also be done using the del keyword. The only difference is that we have to add another pair of square brackets to define the key of nested value. Here is its syntax

Syntax

del MyDict[key][nestedKey]

Code

Now, Lets took an 👀 at some of the dictionaries methods in python:

Dictionary Methods

Python has a set of built-in methods that can be very useful:

  • Copy
    This method returns a copy of the dictionary. So, what is the difference when we use the = assignment operator?

When we use the copy method we create a new dictionary that is the same as the original one. It does not modify the original dictionary.

The assignment operator (=) doesn’t create a new object instead it references the original object. So when do changes to the variable that we made using ‘=’ it affects the original object. So, if we create a variable that points it to our dictionary, it will modify the original dictionary when we modify it

Now let’s use this copy function in code:

MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
newDict = MyDict.copy()print(MyDict) # {'FirstName': 'Default1', 'LastName': 'Default1'}
  • clear
    Removes all the items from the dictionary
MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
MyDict.clear()print(MyDict) # {}
  • keys
    Returns a list containing all the dictionary keys
MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
MyDict.keys() # dict_keys(['FirstName', 'LastName'])
  • values
    Returns a list containing all the dictionary values
MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
MyDict.values() # dict_values(['Default1', 'Default1'])
  • items
    return a list containing all the dictionary’s keys with values as Tuple.

A tuple is a built-in data type in python and like lists, they are used to store multiple items in a single variable. The main difference between list and tuple is that tuples are immutable(can’t be changed) whereas lists are mutable(can be changed) and tuples use parenthesis ‘()’ whereas lists use square brackets. Lists have many built many methods available than tuples but lists consume more memory than tuples.

MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
MyDict.items() # dict_items([('FirstName', 'Default1'), ('LastName', 'Default1')])

Now let’s look at how do we loop through the dictionary in python

Loop In Dictionaries

As we did ‘for loops’ from the Loops and Ranges course to loop through strings and Learn Python For Beginners (Part-2) course to loop through lists, now, let’s loop through dictionaries.

We can loop through a dictionary either through all the

  • Keys
  • Value
  • Both keys and values

Loop through all Keys

MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
for x in MyDict.keys():
print(x)

Or

MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
for x in MyDict:
print(x)

Loop through all Values

MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
for x in MyDict.values():
print(x)

Or

MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
for x in MyDict:
print(MyDict[x])

Loop through Both Keys and Values

MyDict = {
"FirstName":"Default1",
"LastName":"Default2"
}
for key,value in MyDict.items():
print(key + ':' + value)

Here ☝️☝️ for key ,value in .... means that: for each key in the dictionary and for each,valuein the dictionary do something(i.e print)

Thank You !!!

This post was originally published at https://www.decodebuzzing.com

--

--

Jainharsh
Nerd For Tech

Hi folks! I am Harsh Vardhan Jain, you can call me HVJ, I aim to learn together and share my thoughts on developments in the coding world