Dictionaries
Think of a Python dictionary like a magical bag where you can store lots of items, but instead
of just putting them inside randomly, you give each item a special tag so you can find it
easily later.
Bag: Imagine you have a special bag that can hold many things. This bag is like a Python
dictionary.
Items and Tags: Inside the bag, you can put different items like toys, books, snacks, etc. But
here's the cool part: for each item you put in, you also attach a tag to it. This tag is a special
label that describes what the item is or helps you remember where you put it.
Finding Things: Now, when you want to find something in your bag, you don't need to search
through everything. You just look at the tag, and it tells you exactly where to find the item
you're looking for.
In Python, these "items" are called keys, and the "tags" attached to them are called values. So, a
Python dictionary is like a magical bag where you store pairs of keys and values. When you want to
find a value, you just need to know its corresponding key.
Step 1: Create a file “dictionaries.py” (as per your choice)
Step 2: Open the file in editor of your choice (VS Code, notepad++, or notepad)
Creating the Dictionary
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The keys Name and Age are the strings which comes under the category
of an immutable object.
Let's see an example to create a dictionary and print its content.
Example 1: Creating dictionary
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
Example 2:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output
Step 3: Accessing the dictionary values
Example 3:
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output
Step 4: Adding Dictionary Values
Example - 1:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Output
Example - 2:
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output
Step 5: Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Example 1:
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output
Deleting Elements using pop() Method
Example 2:
# Creating a Dictionary
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dict1.pop(2)
print(Dict1)
Output
Step 6: Iterating Dictionary
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(x)
Output
Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(Employee[x])
Output
Example - 3
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.values():
print(x)
Output
Example 4
#for loop to print the items of the dictionary by using items() method
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.items():
print(x)
Output
Step 7: Properties of Dictionary Keys
In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value
for a single key, then the value which is last assigned is considered as the value of the key.
Example 1:
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
"John"}
for x,y in Employee.items():
print(x,y)
Output
Step 8: Built-in Dictionary Functions
len()
The dictionary's length is returned via the len() function in Python. The string is lengthened
by one for each key-value pair.
Example 1:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
len(dict)
Output
any()
Like how it does with lists and tuples, the any() method returns True indeed if one dictionary
key does have a Boolean expression that evaluates to True.
Example 1:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
any({'':'','':'','3':''})
Output
all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True
Boolean value.
Example 1:
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
all({1:'',2:'','':''})
Output
sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series of the
dictionary's keys. The ascending sorting has no effect on the original Python dictionary.
Example 1:
dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
sorted(dict)
Output
Step 9: Built-in Dictionary method
clear()
It is mainly used to delete all the items of the dictionary.
Example 1:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
dict.clear()
print(dict)
Output
copy()
It returns a shallow copy of the dictionary which is created.
Example 1:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
print(dict_demo)
Output
pop()
It mainly eliminates the element using the defined key.
# dictionary methods
Example 1:
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# pop() method
dict.pop(1)
print(dict)
Output
popitem()
removes the most recent key-value pair entered
# dictionary methods
Example 1:
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# popitem() method
dict.popitem()
print(dict)
Output
keys()
It returns all the keys of the dictionary.
Example 1:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# keys() method
print(dict.keys())
Output
items()
It returns all the key-value pairs as a tuple.
# dictionary methods
Example 1:
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# items() method
print(dict.items())
Output
get()
It is used to get the value specified for the passed key.
Example 1:
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# get() method
print(dict.get(3))
Output
update()
it mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary.
# dictionary methods
Example 1:
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict.update({3: "TCS"})
print(dict_demo)
Output
values()
It returns all the values of the dictionary with respect to given input.
# dictionary methods
Example 1:
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# values() method
print(dict.values())
Output