|
|
| Introduction | Variables | If-else |
| Strings | Functions | while-loop |
| For-Loop | List | Set |
| Dictionary | Tuple | Try..Except |
| Class/Object | Inheritance | Polymorphism |
| File Handling | ||
Dictionaries in python allow us to connect pieces of related information. For example we can create a dictionary student that have information like student name, address, major, overall gpa. A dictionary in python is a collection of key-value pairs. Each key has a value. Key's value can be a number, string, a list or even another dictionary. Infact object created in python can be used as dictionary. A key-value pair is a set of values associated with each other. When you provide key, python returns a value associated with it.
The easiest way to create a dictionary is with set of braces {}. This creates an empty dictionary.Each key-value pair can be added to the empty dictionary. Python dictionary can also be created using dict() constructor. Keys in dictionary are case sensitive. For example, key name 'StudentId' is not same as key name 'StudentID'. Python does not allow duplicate keys. A duplicate key overwrite the previous value. keys can be strings, numbers or tuples but not lists are not allowed as keys.
Code Example 1:
#Creates empty dictionary
d1={}
d1["student"]="Mike"
d1["GPA"]=3.34
d1["Major"]="MBA"
#print
print(d1)
#Output:
{'student':'Mike','GPA':3.34, 'Major':'MBA'}
Code Example 2:
#Creates a dictionary
d2 = {1: 'Apple', 2: 'Banana', 3: 'Grapes'}
#print
print(d2)
#Output:
{1: 'Apple', 2: 'Banana', 3: 'Grapes'}
Code Example 3:
#create dictionary using dict()
d3 = dict(a = "Red", b = "Green", c = "Blue")
#print
print(d3)
#Output:
{'a': 'Red', 'b': 'Green', 'c': 'Blue'}
Code Example 4:
#Duplicates are not allowed
carDict = {
"brand": "Honda",
"model": "Civic",
"year": 2015,
"year": 2020
}
#print
print(thisdict)
#Output:
{'brand':'Honda','model':'Civic','year':2020}
To modify a value in dictionary, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key. Dictionary does not allow duplicates. If you add an existing key again with a new value, the old value of the key will be overwritten by the new value. Let us see some examples of dictionary modification.
Code Example 5:
#Create Dictionary:
studentDict={}
studentDict["Name"]="David"
studentDict["Major"]="Maths"
studentDict["GPA"]=3.68
#change the GPA.
studentDict["GPA"]=3.90
#print
print(thisdict)
#Output:
{'Name':'David','Major':'Maths','GPA': 3.9}
Sometimes it becomes necessary to remove the keys from the dictionary if the data stored in that key is no longer required. There are several ways to remove the keys from Python dictionary. pop() method with the key values can remove the key-value pair and return the value of removed key. Another way to delete the key-value pair from dictionary is to use the del() method and pass the key that needs to be deleted. let's see some examples for both methods.
Code Example 6:
#Remove a key using pop()
carDict={}
carDict["Make"]= "Honda",
carDict["Model"]= "Civic"
carDict["Year"]= 2021
yrRemoved=carDict.pop("Year")
#print
print(f"Year removed: {yrRemoved}")
print(f"carDict: {carDict}")
#Output:
Year removed: 2021
carDict:{'Make':'Honda','Model':'Civic'}
Code Example 7:
#Remove a key using del
studentDict = {}
studentDict["Name"]= "John"
studentDict["Major"]= "History"
studentDict["GPA"]= 3.6
studentDict["High-School-GPA"]= 3.8
del studentDict["High-School-GPA"]
#print
print(studentDict)
#Output:
{'Name':'John','Major':'History','GPA': 3.6}
Sometimes you want to remove all the key-values from the dictionary when the data elements in the dictionary are obsolete or no longer required. In that case, clear() method can be used. It will remove all the existing key-values from the dictionary and makes it empty. New keys and values can be added later. Lets see an example of clear() method.
Code Example 8:
#Clear all items
CountyDict={}
CountyDict["County"]= "France"
CountyDict["Capital"]= "Paris"
CountyDict["Official_Language"]= "French",
CountyDict.clear()
#print
print(CountyDict)
#Output:
{}
To get the value a associated with a key, give the name of the dictionary and then place the key inside a set of square brackets. The will return the value associated with that particular key. Once the value of the key is accessed, it can be assigned to a variable. To modify a value in a dictionary, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key. Let's see some examples how to access and modify the keys in a dictionary.
Code Example 8:
#This creates a dictionary
Fav_Colors={"John":"Yellow", "Randy":"Blue", "Mary":"White"}
#To access John's favorite color
Fav_Color_John=Favorite_Colors["John"]
#print
print(f"John's Favorite color is:{Fav_Color_John}")
#Output:
John's Favorite color is:Yellow
Code Example 9:
#update John's favorite color
Fav_Colors["John"]="Green"
#update Mary's favorite color
Fav_Colors["Mary"]="Purple"
#print
print(f"John's Favorite color: {Fav_Colors["John"]}")
print(f"Marys's Favorite color: {Fav_Colors["Mary"]}")
#Output:
John's Favorite color: Green
Mary's Favorite color: Purple
A single python dictionary can contain just a few key-value pairs or millions of pairs. Because dictionary contains large amount of data, Python lets you
loop through a dictionary. You can loop though all the of the dictionary's key-value pairs through its keys or through its values. To loop through all the keys use the key() method and to loop through all the values, use the values() method.
When you use for-loop to loop through a dictionary, you can get all the keys. Once you know the key, you can access the corresponding value.
Using the items() method, you can loop through both the keys and the corresponding values
Code Example 10:
#This creates a dictionary
Fav_Sport={"John":"Baseball", "Randy":"Football"}
#print
#Print all key names in the dictionary
for x in Fav_Sport:
print(x)
#Output:
John
Randy
Code Example 11:
#Print all values in dictionary
for x in Fav_Sport:
print( Fav_Sport[x])
#Output:
Baseball
Football
Code Example 12:
#keys() method to return the keys of a dictionary
for x in Fav_Sport.keys():
print(x)
#Output:
John
Randy
#values() method to return the values of a dictionary
for x in Fav_Sport:
print( Fav_Sport[x])
#Output:
Baseball
Football
Code Example 13:
#Return keys and values, by using the items()
for x, y in Favorite_Sport.items():
print(f"{x} - {y}")
#Output:
John - Baseball
Randy - Football