Dictionary

Introduction

 

Python dictionaries are other types of data structures like lists or tuples but they function in a very specific way: they are indexed by keys and their respective values.

 

d = {
    : ,
    : ,
      .
      .
      .
    :
}


We can initialize the key value pair in the below format,

dict1= {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}   


Or we can initialize it incrementally,

dict1= {}
dict1["brand"] = "Toyota"
dict1["color"] = "black"
dict1["model"] = "Yaris"


A tuple can also be a dictionary key, because tuples are immutable:

Dict-tuple = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}    


So elements can be added that way too.

Accessing Dictionary

Has length 5 and can be indexed like this:

 

key

value

"brand"

"Toyota"

"color"

"black"

"model"

"Yaris"

 

print( dict1["brand"] ) #prints the value with key "brand"
print( dict1["color"] ) #prints the value with key "color"
print( dict1["model"] ) #prints the value with key "model"

 

Output:

Toyota
black
Yaris


We can iterate over the list created by Dict1.keys() and get the keys:

for k in dict1.keys():
    print(k)

 

Output:

brand
color
model


We can iterate over the list created by dict1.values() and get the values:

for v in Dict1.values():
    print(v)

 

Output:

Toyota
black
Yaris

 

We can iterate over the list of tuples created by dict1.items() and get the pair key-value:

for k,v in dict1.items():
    print(k,v)

 

Output:

brand Toyota
color black
model Yaris


Operations

Membership
 

There is a way to finding out if a specific key exists in a specific dictionary but only works for keys. Example:

print( "brand" in dict1)

 

Output: True


This will print out True because the key “brand” indeed exists in Dict1. Example:

print( "Toyota" in dict1.values())    

 

Output: True


This will print out True because the value “Toyota” key indeed exists in dict1. Example:

print( ("brand","Toyota") in dict1.items())   

 

Output: True


This will print out True because the pair (“brand”,” Toyota”) indeed exists in dict1.

Working with Dictionaries

Dictionaries and lists share the following characteristics:
•    Both are mutable.
•    Both are dynamic. They can grow and shrink as needed.
•    Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

Dictionaries differ from lists primarily in how elements are accessed:
•    List elements are accessed by their position in the list, via indexing.
•    Dictionary elements are accessed via keys.

 

Function and Methods

 

Function

Description

E.g

dict.clear()

It removes all the elements.

Dict1.clear() clears the entire dictionary

Dict1 is now {} (an empty dictionary)

dict.get(key)

Returns the value of a specific key.

Dict1.get("color") will return the String "black"

dict.items()

Returns a list of tuples containing the key-value pairs in dict.

Dict1.items() returns the list of tuples: [("brand", "Toyota"), ("color", "black"), ("model", "Yaris")]

dict.keys()

Returns a list of all keys in dict.

Dict1.keys() will return the list:

["brand","color","model"]

dict.values()

Returns a list of all values in dict.

Dict1.values() will return the list:

["Toyota","black","Yaris"]

dict.Pop(key)

Removes key-value pair with specific key. Much like remove in lists or tuples.

Dict.pop("brand") will remove the key-value pair with the key "brand"

Dict.popitem()

It removes and returns the last object of the dict as a tuple.

print(Dict1.popitem())removes the pair "brand" : "Yaris" and returns the tuple ("brand", "Yaris").

dict.update(obj)

If obj is of type dictionary then dict will be added that dictionary. If a key-value pair already exists then that value for that key is updated.

Dict1.update({"color" : "white", "autopilot" : false}) will update the value of the color to white and add the field autopilot


dict.clear():

 

dict1= {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
print( dict1.clear())

 

Output: None

 

dict.get(key):

 

dict1= {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
print( dict1.get("color"))

 

output:Black

 

dict.items():

 

dict1= {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
print( dict1.items())

 

Output: dict_items([('brand', 'Toyota'), ('color', 'black'), ('model', 'Yaris')])

 

dict.keys():

 

dict1= {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
print( dict1.keys())

 

Output: dict_keys(['brand', 'color', 'model'])


dict.values():

 

dict1 = {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
print( dict1.values())

 

Output: dict_values(['Toyota', 'black', 'Yaris'])

 

dict.Pop(key):

 

dict1 = {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
print( dict1.pop("brand"))

 

Output: Toyota

 

dict.popitem():

 

dict1= {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
print( dict1.popitem())

 

Output: ('model', 'Yaris')

 

dict.update(obj):

 

dict1= {"brand" : "Toyota", "color" : "black", "model" : "Yaris"}
dict2= {"color" : "white", "autopilot" : False}
dict1.update(dict2)
print( dict1)

 

Output: {'brand': 'Toyota', 'color': 'white', 'model': 'Yaris', 'autopilot': False}

 

Related Tutorials