Python Dictionaries
Python Dictionaries
Dictionaries are a useful data structure for storing data in Python because they are capable of
imitating real-world data arrangements where a certain value exists for a given key.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python
object. The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers.
Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are
generally unordered.
Curly brackets are the simplest way to generate a Python dictionary, although there are other
approaches as well. With many key-value pairs surrounded in curly brackets and a colon separating
each key from its value, the dictionary can be built. (:). The following provides the syntax for
defining the dictionary.
Syntax:
In the above dictionary Dict, The keys Name and Age are the strings which comes under the
category of an immutable object.
Code
Page 1 of 17
1. Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to create the dictionary.
Code
Page 2 of 17
Output
Empty Dictionary:
{}
Create Dictionary by using dict():
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
Dictionary with each item as a pair:
{4: 'Rinku', 2: 'Singh'}
To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary
can be used to obtain the values because they are unique from one another. The following method
can be used to access dictionary values.
Code
Output
ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Page 3 of 17
Salary : 45000
Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary values. It
would give the same result as given by the indexing.
The dictionary is a mutable data type, and utilising the right keys allows you to change its values.
Dict[key] = value and the value can both be modified. An existing value can also be updated using
the update() method.
Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the
dictionary's newly added keys.
Example - 1:
Code
Page 4 of 17
14. # The Emp_ages doesn't exist to dictionary
15. Dict['Emp_ages'] = 20, 33, 24
16. print("\nDictionary after adding 3 elements: ")
17. print(Dict)
18.
19. # Updating existing Key's Value
20. Dict[3] = 'JavaTpoint'
21. print("\nUpdated key value: ")
22. print(Dict)
Output
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Example - 2:
Code
Page 5 of 17
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)
Output
<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the details
of the new employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}
The items of the dictionary can be deleted by using the del keyword as given below.
Code
Page 6 of 17
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
The last print statement in the above code, it raised an error because we tried to print the Employee
dictionary that already deleted.
A dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove items
using this unordered, mutable data type by using their keys. The pop() method is one of the ways
to get rid of elements from a dictionary. In this post, we'll talk about how to remove items from a
Python dictionary using the pop() method.
The value connected to a specific key in a dictionary is removed using the pop() method, which
then returns the value. The key of the element to be removed is the only argument needed. The
pop() method can be used in the following ways:
Code
1. # Creating a Dictionary
2. Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
Page 7 of 17
3. # Deleting a key
4. # using pop() method
5. pop_key = Dict1.pop(2)
6. print(Dict1)
Output
Additionally, Python offers built-in functions popitem() and clear() for removing dictionary items.
In contrast to the clear() method, which removes all of the elements from the entire dictionary,
popitem() removes any element from a dictionary.
Iterating Dictionary
Example 1
Code
Output
Name
Age
salary
Company
Example 2
Page 8 of 17
Code
Output
John
29
25000
WIPRO
Example - 3
Code
1. #for loop to print the values of the dictionary by using values() method.
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.values():
4. print(x)
Output
John
29
25000
WIPRO
Example 4
Code
1. #for loop to print the items of the dictionary by using items() method
Page 9 of 17
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.items():
4. print(x)
Output
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')
1. 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.
Code
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
2. "John"}
3. for x,y in Employee.items():
4. print(x,y)
Output
Name John
Age 29
Salary 25000
Company WIPRO
2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples can be used
as the key, however mutable objects like lists cannot be used as the key in a dictionary.
Page 10 of 17
Consider the following example.
Code
Output
A function is a method that can be used on a construct to yield a value. Additionally, the construct
is unaltered. A few of the Python methods can be combined with a Python dictionary.
The built-in Python dictionary methods are listed below, along with a brief description.
o len()
The dictionary's length is returned via the len() function in Python. The string is lengthened by one
for each key-value pair.
Code
Output
Page 11 of 17
4
o 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.
Code
Output
True
o all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a True
Boolean value.
Code
Output
False
o 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.
Code
Page 12 of 17
2. sorted(dict)
Output
[ 1, 5, 7, 8]
The built-in python dictionary methods along with the description and Code are given below.
o clear()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # clear() method
4. dict.clear()
5. print(dict)
Output
{}
o copy()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
Page 13 of 17
5. print(dict_demo)
Output
o pop()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # pop() method
4. dict_demo = dict.copy()
5. x = dict_demo.pop(1)
6. print(x)
Output
popitem()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # popitem() method
4. dict_demo.popitem()
5. print(dict_demo)
Output
Page 14 of 17
{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}
o keys()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # keys() method
4. print(dict_demo.keys())
Output
dict_keys([1, 2, 3, 4, 5])
o items()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # items() method
4. print(dict_demo.items())
Output
dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
o get()
Code
Page 15 of 17
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # get() method
4. print(dict_demo.get(3))
Output
Facebook
o update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this dictionary.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # update() method
4. dict_demo.update({3: "TCS"})
5. print(dict_demo)
Output
It returns all the values of the dictionary with respect to given input.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # values() method
4. print(dict_demo.values())
Page 16 of 17
Output
Page 17 of 17