Table of contents
Dictionaries
Dictionaries is another data structure in python like Lists. In dictionary, we can store our data as key and value pair.
Dictionary = {key: Value}
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
}
In the below snippet, you can see how we can perform different operations on dictionary data structure in python.
#Retrive item from dictionary
#key must be used with its datatype
print(programming_dictionary["Bug"])
#Adding items into dictionary
programming_dictionary["Loop"] = "The action of doing something again and again"
#print(programming_dictionary)
#Create an empty dictionay
empty_dictionary = {}
#Wipe an exsiting dictionary
programming_dictionary = {}
print(programming_dictionary)
#Editing an item in a dictionary
programming_dictionary["Bug"] = "Amoth in your computer"
#print(programming_dictionary)
#Loop through your dictionary
for key in programming_dictionary:
print(key)#It will return keys of dictionary
print(programming_dictionary[key])#It will return values of key form dictionary
Nesting Lists and Dictionaries
###############
#Nesting a list into a dictionary
travel_log = {
"France": ["Paris","Lille","Digin"],
"Germany": ["Berlin","Hamburg","Stuttgart"],
}
#Nesting Dictionary inside Dictionary
travel_log = {
"France": {"cities_visited":["Paris","Lille","Digin"],"total_visits":12},
"South Korea": {"cities_visited":["Soul","Jeju","Bussan"],"total_visits":0},
}
#Nesting a dictionary inside a List
travel_log = [
{
"Country": "France",
"cities_visited": ["Paris","Lille","Digin"],
"total_visits": 12
},
{
"Country": "South Korea",
"cities_visited": ["Soul","Jeju","Bussan"],
"total_visits": 0
},
]
Project
Using dictionary I have wrote The Secret Auction Program. Where bidder secretly add bidding values and the one added highest value win the bid. For day 9 exercises and project head-over to my GitHub repository.