0% found this document useful (0 votes)
62 views14 pages

List Declaration-Programs

The document discusses Python lists and dictionaries. It provides examples of creating, accessing, modifying, and deleting elements in lists and dictionaries. Some key points covered include how lists are ordered collections that can contain different data types, while dictionaries contain key-value pairs and allow accessing values via keys.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views14 pages

List Declaration-Programs

The document discusses Python lists and dictionaries. It provides examples of creating, accessing, modifying, and deleting elements in lists and dictionaries. Some key points covered include how lists are ordered collections that can contain different data types, while dictionaries contain key-value pairs and allow accessing values via keys.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

List Declaration

Code

1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10. print(type(list1))
11. print(type(list2))

Output:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >

Characteristics of Lists
The characteristics of the List are as follows:

ADVERTISEMENT
ADVERTISEMENT

o The lists are in order.


o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.

Ordered List Checking


Code

1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b

Output:

False
The indistinguishable components were remembered for the two records; however,
the subsequent rundown changed the file position of the fifth component, which is
against the rundowns' planned request. False is returned when the two lists are
compared.

Code

1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b

Output:

True

Records forever protect the component's structure. Because of this, it is an arranged


collection of things.

Let's take a closer look at the list example.

Code

1. # list example in detail


2. emp = [ "John", 102, "USA"]
3. Dep1 = [ "CS",10]
4. Dep2 = [ "IT",11]
5. HOD_CS = [ 10,"Mr. Holding"]
6. HOD_IT = [11, "Mr. Bewon"]
7. print("printing employee data ...")
8. print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
9. print("printing departments ...")
10. print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( De
p1[0], Dep2[1], Dep2[0], Dep2[1]))
11. print("HOD Details ....")
12. print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
13. print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
14. print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))

Output:

printing employee data...


Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class
' list '>

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.

ADVERTISEMENT

ADVERTISEMENT

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

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)

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

ADVERTISEMENT

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

ADVERTISEMENT

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Adding elements to dictionary one at a time
7. Dict[0] = 'Peter'
8. Dict[2] = 'Joseph'
9. Dict[3] = 'Ricky'
10. print("\nDictionary after adding 3 elements: ")
11. print(Dict)
12.
13. # Adding set of values
14. # with a single Key
15. # The Emp_ages doesn't exist to dictionary
16. Dict['Emp_ages'] = 20, 33, 24
17. print("\nDictionary after adding 3 elements: ")
18. print(Dict)
19.
20. # Updating existing Key's Value
21. Dict[3] = 'JavaTpoint'
22. print("\nUpdated key value: ")
23. 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: "));
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)
ADVERTISEMENT

ADVERTISEMENT

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");
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.

ADVERTISEMENT

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

ADVERTISEMENT

Name
Age
salary
Company

Example 2
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 Employ
ee:
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
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.items():
4. print(x)

Output

ADVERTISEMENT

ADVERTISEMENT

('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.

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

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


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

{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

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

Output

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

You might also like