[go: up one dir, main page]

0% found this document useful (0 votes)
44 views17 pages

Python Dictionaries

The document provides an overview of Python dictionaries, explaining their structure as key-value pairs, mutability, and the types of keys and values allowed. It covers how to create, access, update, and delete dictionary entries, along with built-in methods for manipulating dictionaries. Additionally, it discusses properties of dictionary keys and provides examples of various operations on dictionaries.

Uploaded by

firdaushussain56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views17 pages

Python Dictionaries

The document provides an overview of Python dictionaries, explaining their structure as key-value pairs, mutability, and the types of keys and values allowed. It covers how to create, access, update, and delete dictionary entries, along with built-in methods for manipulating dictionaries. Additionally, it discusses properties of dictionary keys and provides examples of various operations on dictionaries.

Uploaded by

firdaushussain56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PYTHON DICTIONARY

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.

The data is stored as key-value pairs using a Python dictionary.

o This data structure is mutable


o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.

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.

Creating the Dictionary

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:

1. 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.

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.

The empty curly braces {} is used to create empty dictionary.

Code

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Creating a Dictionary
7. # with dict() method
8. Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
9. print("\nCreate Dictionary by using dict(): ")
10. print(Dict)
11.
12. # Creating a Dictionary
13. # with each item as a Pair
14. Dict = dict([(4, 'Rinku'), (2, Singh)])
15. print("\nDictionary with each item as a pair: ")
16. print(Dict)

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'}

Accessing the dictionary values

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

1. Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])

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.

Adding Dictionary Values

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.

Let's see an example to update the dictionary values.

Example - 1:

Code

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5. # Adding elements to dictionary one at a time
6. Dict[0] = 'Peter'
7. Dict[2] = 'Joseph'
8. Dict[3] = 'Ricky'
9. print("\nDictionary after adding 3 elements: ")
10. print(Dict)
11.
12. # Adding set of values
13. # with a single Key

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

1. Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));

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'}

Deleting Elements using del Keyword

The items of the dictionary can be deleted by using the del keyword as given below.

Code

1. Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");

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.

Deleting Elements using pop() Method

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

{1: 'JavaTpoint', 3: 'Website'}

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

A dictionary can be iterated using for loop as given below.

Example 1

Code

1. # for loop to print all the keys of a dictionary


2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee:
4. print(x)

Output

Name
Age
salary
Company

Example 2

Page 8 of 17
Code

1. #for loop to print all the values of the dictionary


2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"} for x in Empl
oyee:
3. print(Employee[x])

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')

Properties of Dictionary Keys

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.

Consider the following example.

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

1. Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"


Department ID"}
2. for x,y in Employee.items():
3. print(x,y)

Output

Traceback (most recent call last):


File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29,
"salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

Built-in Dictionary Functions

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

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. len(dict)

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

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. any({'':'','':'','3':''})

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

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. all({1:'',2:'','':''})

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

1. dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}

Page 12 of 17
2. sorted(dict)

Output

[ 1, 5, 7, 8]

Built-in Dictionary methods

The built-in python dictionary methods along with the description and Code are given below.

o clear()

It is mainly used to delete all the items of the dictionary.

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()

It returns a shallow copy of the dictionary which is created.

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

{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

o pop()

It mainly eliminates the element using the defined key.

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

{2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

popitem()

removes the most recent key-value pair entered

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()

It returns all the keys of the dictionary.

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()

It returns all the key-value pairs as a tuple.

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()

It is used to get the value specified for the passed key.

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

{1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}


o values()

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

dict_values(['Hcl', 'WIPRO', 'TCS'])

Page 17 of 17

You might also like