Loading, please wait...

A to Z Full Forms and Acronyms

All About Python Dictionary | Python Dictionary Tutorial

This article is all about python dictionary & operations that we can perform on it.

What is Dictionary in Python?

A dictionary in Python is a collection(which is unordered, changeable, and indexed) of items accessed by specific key rather than by index. In the real world, when we need to look up the meaning of a word then we try to find the meaning using the word itself and not the possible index of the word in the dictionary, Python dictionaries work with the same concept, the word whose meaning we are looking for is a key and its meaning is the value.

We don't need to know the index of the word in a dictionary to find its meaning. Python Dictionary is initialized by curly braces.

Syntax:

pydict = {
             "key1": "value1" ,
             "key2": "value1",
              .
              .
              .
              "keyn" : "value n"
           }

Now, let's discuss the python dictionary in brief.

How to create & Print Dictionary

cardict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(cardict)

#output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

How to Access Items from Dictionary?

We can access the items of a dictionary by referring to its key name, inside square brackets:

Example: Get the value of the "model" key:

model_name = cardict["model"]

print(model_name)
#output: Mustang

Note: There is also a method called get() that will give you the same result:

#Example:Get the value of the "model" key:

model_name = cardict.get("model")
print(model_name)
#output:
Mustang

How to change the value in Dictionary?

We can change the value of a specific item by referring to its key name:

#Example

#Change the "year" to 2020:
cardict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
cardict["year"] = 2020
print(cardict)

#output:{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

HOW TO LOOP through a DICTIONARY?

We can loop through a dictionary by using a 'for ' loop.

When looping through a dictionary, the return value is the keys of the dictionary, 

but there are methods to return the values as well so let's see-through code how we can do this.

EXAMPLE: Printing all key names in the dictionary, one by one:

for x in cardict:
  print(x)

#output
brand
model
year

Printing all values in the dictionary, one by one:

for x in cardict:

  print(cardict[x])
#output:
Ford
Mustang
1964

 We can also use the values() method to retrieve the values of a dictionary:

for x in cardict.values():

  print(x)
#output:
Ford
Mustang
1964

We can also Loop through both keys and values, by using the items() method:

for x, y in cardict.items():
  print(x, y)
#ouptut:
brand Ford
model Mustang
year 1964

Now let's see how we can check whether the key is present in a dictionary:  To determine if a specified key is present in a dictionary using the 'in' keyword:

Now let's check if "model" is present in the dictionary:

cardict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in cardict:
   print("Yes, 'model' is one of the keys in the "cardict" dictionary")

#output:Yes, 'model' is one of the keys in the dictionary

How to check the Length of the Dictionary?

Now let's see how many items (key-value pairs) a dictionary has, To determine this we can use the len() function.

Result={
         "English": 89,
         "Hindi": 90,
         "Maths": 99,
         "Science":99
}

#Print the number of items in the dictionary:
print(len(Result))
#output: 4

How to add an item to Dictionary?

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

cardict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
cardict["color"] = "White"
cardict["Price"] = 10,050,000
print(cardict)

#output:{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White', 'Price': 10050000}

How to Remove Item from Dictionary in Python?

There are several methods to remove an item or items from a dictionary, let's see some of the methods :

1.use of pop() method: The pop() method removes the item with the specified key name:

cardict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964,
    "color": "White",
    "Price": 10,050,000
}
print(cardict.pop("model"))

#output:Mustang

Note: The popitem() method removes the last inserted item of the dictionary

cardict = {
 "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
cardict.popitem()
print(cardict)

#output:('year', 1964)

2. use of del keyword: 

The del keyword removes the item with the specified key name, let's see the code how we can use the 'del' keyword:

Result={
         "English": 89,
         "Hindi": 90,
         "Maths": 99,
         "Science":99
}
del Result["English"]
print(Result)
#output:
this will remove the item with the specified key name

The del keyword can also delete the dictionary completely:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict)

#output: NameError: name 'thisdict' is not defined

3. user of clear() method:

The clear() method empties the dictionary:

thisdict = {
   "brand": "Ford",
   "model": "Mustang",
   "year": 1964
}
thisdict.clear()
print(thisdict)
#output: {}

How to Copy Dictionary in Python?

We cannot copy a dictionary simply by writing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

let's see how it works:

newdict = Result

print(newdict)
#output:{'English': 89, 'Hindi': 90, 'Maths': 99, 'Science': 99}

print(Result)
#output:{'English': 89, 'Hindi': 90, 'Maths': 99, 'Science': 99}

Result["Social"]= 89 # new key-value pair]

print(Result)
#output:{'English': 89, 'Hindi': 90, 'Maths': 99, 'Science': 99, 'Social': 89}

print(newdict)
#output:{'English': 89, 'Hindi': 90, 'Maths': 99, 'Science': 99, 'Social': 89}

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

Make a copy of a dictionary with the copy() method:

thisdiet = {

  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

mydict = thisdict.copy()

print(mydict)

thisdict["color"]="red"

print(thisdict)

print(mydict)

Another way to make a copy is to use the built-in function dict().

let's make a copy of a dictionary with the dict() function:

thisdict = {

  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

mydict = dict(thisdict)
print(mydict)
#output:
#{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

What is the Nested Dictionary?

A dictionary can also contain many dictionaries, this is called nested dictionaries. Now let's create a dictionary that contains three dictionaries:

code:

myfamily = {
  "child1" : {"name" : "AVI","year" : 1998},

  "child2" : {"name" : "KAJAL","year" : 2000},

  "child3" : {"name" : "VIBHA","year" : 1998}
}

output:

But, What if we want to nest three dictionaries that already exists as dictionaries, lets see the code for this too:

For this we need to create three dictionaries, then create one dictionary that will contain the other three dictionaries:

code:

child1 = {
  "name" : "Neha",
  "year" : 2004
}

child2 = {
   "name" : "BHUMIKA",
   "year" : 2007
}

child3 = {
  "name" : "BHUVIKA",
  "year" : 2011
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}

output:

DICTIONARY CONSTRUCTOR:

In python, we have dict() constructor to make a new dictionary, this can be used if a programmer wants to create a dictionary in a single line or to reduce the line of code.

Now let's see how we can make a new dictionary using dict() constructor.

code:

student= dict(name ="Monalisa", gender="Female", age =19, id = 2099989876)

print(student)

output:

Dictionary Methods:

Python has several built-in methods that we can use on dictionaries.

  • clear(): To removes all the elements from the dictionary
  • copy(): To returns a copy of the dictionary
  • fromkeys(): To returns a dictionary with the specified keys and value
  • get(): To returns the value of the specified key
  • items(): To returns a list containing a tuple for each key-value pair
  • keys(): To returns a list containing the dictionary's keys
  • pop(): To removes the element with the specified key
  • popitem(): To removes the last inserted key-value pair
  • setdefault(): To returns the value of the specified key. If the key does not exist: insert the key with the specified value
  • update(): It updates the dictionary with the specified key-value pairs
  • values(): It returns a list of all the values in the dictionary

Use of key(), value() & item() methods: 

#key(), values(), items()

myfamily = {
  "child1" : "ROHAN",
  "child2" : "SUMIT",
  "child3" : "NEHA"
}

#this will print a list of all the keys

print(myfamily.keys())

#this will print a list of all values

print(myfamily.values())

#this will print a list of all keys and values

print(myfamily.items())

Now let's write a code that counts the frequency of each 'letter' of str1 variable and appends the letter as key and frequency as the value in the dictionary.

code:

str1= 'www.tutorialslink.com'
dict1={}
for letter in str1:

    if letter not in dict1:
       dict1[letter]=1
       print(dict1)

    else:

        dict1[letter]= dict1[letter] +1
        print(dict1[letter])

output:

A to Z Full Forms and Acronyms

Related Article