List and Dictionary Manipulation in Python

HELLO Pythonists, today we are going to learn about List and Dictionary manipulation in Python.

Before we dive deep into our main topic lets have a basic introduction to Lists and Dictionaries in Python.

Introduction

  • List

A list is a data structure in Python. The list has comma-separated values written between square brackets.

A list is mutable. i.e.-: Lists can be modified after creation.

A list is an ordered sequence of items. The order of the sequence of the list starts with ‘0’. We can perform various operations on a list.

  • Dictionary

A dictionary is a mutable datable. We can modify a Dictionary after its creation.

Dictionary is an unordered set. It consists of key-pair values, where each key is unique.

In Python, we create dictionaries using curly brackets.

So let us move onto the main topic of manipulation.

Dictionary manipulation

In Python, dictionaries are written using curly brackets. They have key-value pairs separated by commas.

Example:

empl={'firstname': 'tirthesh', 'lastname':'pawar','empid':'443','emploc':'mumbai'}
print(empl)
{'firstname': 'tirthesh', 'lastname': 'pawar', 'empid': '443', 'emploc': 'mumbai'}

Accessing values in a dictionary have a quite simple syntax as follows:

>>> empl['firstname']
'tirthesh'
>>> empl['lastname']
'pawar'
>>> empl['empid']
'443'
>>> empl['emploc']
'mumbai'

We can update a dictionary as follows:

empl.update({'empid':'444'})

Here we used the .update() method.
Let us display the updated value of the key ’empid’

>>>print(empl['empid'])
444

Another method of updating the dictionaries is using the assignment operator:

empl={'firstname': 'tirthesh', 'lastname':'pawar','empid':'443','emploc':'mumbai'}
empl['emploc']='bangalore'
print(empl)

So the following is the outcome of the above lines of code:

{'firstname': 'tirthesh', 'lastname': 'pawar', 'empid': '443', 'emploc': 'bangalore'}

The outcome of emploc has changed from Mumbai to Bangalore.

Accessing a non-existent element without error using getmethod():

Any attempts to access an element through a key that is non-existent will result in a ‘KeyError’ message.

We may use the .get() method to overcome this error. The .get() method takes a key as a first argument and a fallback value as the second.

  • Without the .get() method KeyError occurs:
>>> empl={'firstname': 'tirthesh', 'lastname':'pawar','empid':'443','emploc':'mumbai'}
>>> #this is the key that is non existent and hence will get a KeyError
>>> empl['middlename']

Output:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    empl['middlename']
KeyError: 'middlename'

Accessing a non-existent element using getmethod():

  • With the .get() method Key error does not occur:
>>> empl={'firstname': 'tirthesh', 'lastname':'pawar','empid':'443','emploc':'mumbai'}
>>> empl.get('middlename','no_value')

Output:

'no_value'

So now that we have seen a few dictionary manipulation techniques let us move onto the list manipulation techniques.

List manipulation

Lists are written in square brackets [].

Lists are ordered.

The order of lists starts from value ‘0’.

Creation of lists:

empidList=[400,401,402,403,404]
print(empidList)

Output:

[400, 401, 402, 403, 404]

Now suppose we have to access the third element in this list. Let me remind you before accessing the third element in this list that lists start from the order value ‘0’. So we will go for the value ‘2’ in the syntax. Below is the demonstration along with the output for clear understanding.

Accessing the list:

empidList=[400,401,402,403,404]
print(empidList[2])

Output:

402

As we can observe 402 is the third element in the list. It is correctly displayed in the output using the above lines of code for accessing the list.

Negative Indexing;

As we observed that lists can be accessed using positive indexes. Similarly, we can do it using negative indexes.

  • -1: is the value for the last element of the list
  • -2:is the value for the second last element of the list
    and so on..

Let us look at an example using the following code:

empidList=[400,401,402,403,404]
print(empidList[-2])

The above code will fetch the second last element of the list using negative indexing.

Output:

403

We can apply a range to an index to access values in those particular ranges.

Following is the demonstration of list access using ranges: both positive and negative

Accessing lists using positive and negative ranges:

empidList=[400,401,402,403,404]
#the below search range starts from starting value 0 till 'n-1' 2. It will display the output till the 2nd value.
print(empidList[0:3])
#This example returns the items from index -4 (included) to index -1 (excluded)
#Remember that the last item has the index -1
print(empidList[-4:-1])
[400, 401, 402]
[401, 402, 403]

Appending and inserting items at the end of the list:

>>> empidList=[400,401,402,403,404]
>>> empidList.append(405)
>>> empidList.insert(406,407)
>>> print(empidList)
[400, 401, 402, 403, 404, 405, 407]

As we can observe the append method and the insert method applied to the list works the same way altogether. Both methods add values to the end of the list.

Conclusion:

So we observed a few methods on list and dictionary manipulations in Python. Try them hands-on for better understanding. Also, I have attached a link below to reduce the length of the code that will save the memory and make the code effective using comprehension methods. Keep Coding!!

Also read: Python | List and Dictionary comprehension

 

Leave a Reply

Your email address will not be published. Required fields are marked *