Working with Lists and Dictionaries in Python

Mohit Last Updated : 21 Oct, 2024
14 min read

Working with lists and dictionaries in Python opens up a world of possibilities for data organization and manipulation. Imagine having a virtual toolbox where you can effortlessly store, retrieve, and modify data as needed—lists are like flexible containers for sequences of items, while dictionaries offer a powerful way to manage key-value pairs, allowing for quick access and updates. Whether you’re handling a collection of cities, tracking sales information, or navigating complex data structures, mastering these fundamental concepts will elevate your programming skills and enable you to tackle real-world challenges with confidence and creativity. Let’s dive into the exciting features and functionalities that lists and dictionaries have to offer!

Working with Lists and Dictionaries in Python

For Beginners, free Python tutorials and libraries like numpy and pandas, you can refer to Introduction to Python.

Learning Objectives

  • Understand the structure and properties of Python lists and dictionaries.
  • Learn how to access, update, and delete elements from lists and dictionaries in Python.
  • Discover methods to manipulate lists, including appending, extending, and sorting.
  • Explore ways to loop through dictionary elements using key-value pairs.
  • Convert Python lists into dictionaries and understand key-value pair manipulation.
  • Apply Python list operations like indexing, slicing, and nested lists for complex data storage.
  • Learn advanced dictionary techniques such as accessing, updating, and iterating through items.

This article was published as a part of the Data Science Blogathon.

What are Lists?

Lists are just like arrays. Python lists are mutable data types in Python. A list refers to the collection of index value pair-like arrays in C/C++/Java. Lists is a 0-based index datatype, meaning the index of the first element starts at 0. Lists are used to store multiple items in a single variable. These are one of the 4 data types present in Python, i.e., Lists, Dictionaries, Tuples & Sets. A list is created by placing elements in [ ] separated by commas ‘, ‘. We can use them to store more complex data structures other than integers, strings, or floats. A list of dictionaries is a great example.

Accessing the List Elements

If there is a concept that is easier and more common than accessing elements in a list in Python, I still have not come across it. Through the use of indexing and slicing you can get, set or fetch portions of the list as you work with data since it is so flexible. It has both post-positive and pre-negative indexing system whereby anyone can begin from the beginning or the end of the list.

Accessing Elements Using Positive Indexing

In Python, the list indices begin with 0 implying that the first element of any list is located at its zeroth index, the second element in the list is at first index, … It is done with equal ease by typing the required index number in square brackets after the list name.

Python Code:

num_list=[10,20,30,40,50,60,70,80,90]
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']

print(city_list[2])
print(num_list[2])

Output:

Ahmedabad
30

Accessing Elements Using Negative Indexing

Python also supports negative indexing, where -1 refers to the last element of the list, -2 refers to the second last element, and so on. This feature is particularly useful when you want to access elements from the end of the list.

print(city_list[-1])

Output:

Coimbatore

Note: If you try to access an index that is out of range, Python will raise an IndexError. So, make sure the index you’re trying to access falls within the valid range of the list.

Understanding Indexing in Python Lists

In Python, indexing is a powerful way to access and manipulate elements within a list. It allows you to retrieve a single element or a range of elements using indices. The ability to specify a range or slice of the list is extremely useful in various data manipulation tasks, enabling you to handle different portions of your list efficiently.

Accessing a Range of Elements Using Slicing

Python allows you to extract a sublist from an existing list using slicing. You define a range of indices, and Python will return the elements between those indices. The syntax for slicing is list[start:stop], where start is the index of the first element you want to include, and stop is the index where slicing ends (excluding the element at this position).

print(city_list[2:5])

Output:

['Ahmedabad', 'Surat', 'Lucknow']

Omitting Start or End Index

When slicing, if you omit the start index, Python will start from the beginning of the list. Similarly, omitting the stop index will include all elements from the start index to the end of the list.

# Slicing from the start to the 3rd index
print(city_list[:3])
# Slicing from the 2nd index to the end
print(city_list[2:])

Output:

['Agra', 'Chennai', 'Ahmedabad']
['Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']

Finding the Index of a List Element

Python’s index() function allows you to find the index value of a specific item in a list, provided the item exists. You can also specify an optional range (start, end) within which Python should search for the item.

print(city_list.index('Chennai',0,3))

Output:

1

Working With Operators in the List

In Python you will find many types of operators that can be used with lists, including concatenation and repetition as well as comparisons. These operators are important to successfully manipulate list data type since they can boost your coding performance and option.

Concatenation Using the + Operator

Without any doubt one of the most frequently used operation which you will probably deal with when working with list is concatenation and in this case you will be glad to know that you can perform this operation using the + operator. This basic and helpful function also helps to combine multiple lists into one united collection and add the elements of one list to another without intervening between them. Just as you can tentatively compile a shopping list and your friend’s, you can instantly bring into being a new list containing what you need! For example:

num_city_list= num_list+ city_list
print(num_city_list)

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']

Repetition Using the * Operator

The * operator aids in repetition of the contents of a list say N times to the list with simplycopying the contents. This applies where one wishes to repeat the same sequence of operations of the automated program or replicate other patterns.

new_citylist= city_list*2
print(new_citylist)

Output:

['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']

List Comparison Using Relational Operators

In Python the comparison of two lists can be done using relational operators like ==,!=, <, >, <= and >=. These comparisons are done one feature at a time, beginning with the first feature of one list and the first feature of the other list. If first elements are equal Python try to compare the second elements and so on accordingly.

  • The == operator checks if two lists have the same elements in the same order.
  • The != operator checks if two lists are not the same.
list1 = [10, 20, 30]
list2 = [10, 20, 30]
list3 = [30, 20, 10]

print(list1 == list2)  # True
print(list1 != list3)  # True

List Containment Using the in Operator

The in operator checks whether a specific element exists within a list, returning True if the element is present and False otherwise. This operator is often used to check membership in a list or search for values.

print('Ahmedabad' in city_list)  # True
print(100 in num_list)  # False

Modifying Lists In-Place Using += and *= Operators

Python also supports the += and *= operators for in-place modification of lists. The += operator appends the elements of another list to the existing list, and the *= operator repeats the list elements in place.

num_list += [100, 110]
print(num_list)  # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]

city_list *= 2
print(city_list)  # ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'

Working with Nested Lists

Nested list is a list that is made up of one or more other list within it. It gives an opportunity to store any kind of more complex data arrangements like matrices, tables or hierarchical structures, and in each element of such structure is a list. When it comes to operating on the data, working with nested lists makes you have the ability to easily manage multi-dimensional data.

Defining Nested Lists

In the example below, list_nest contains two elements, where each element is a list. The first nested list holds integers, and the second one contains strings:

list_nest=[[10,20,30],['a','b','c']]
list_nest

Output:

[[10, 20, 30], ['a', 'b', 'c']]

Accessing Elements in Nested Lists

To access elements within a nested list, you need to use double indexing: the first index selects the sublist, and the second index picks an item from that sublist. This process allows you to navigate through the hierarchy of lists.

The elements of a nested list can be accessed as shown below:

print(list_nest[1][2])

Output:

c

Modifying Elements in Nested Lists

Just like simple lists, elements within a nested list can also be modified using indexing. You can target specific items within the sublists and reassign their values.

list_nest[0][1] = 25
print(list_nest)

Output:

[[10, 25, 30], ['a', 'b', 'c']]

Adding Elements to Nested Lists

You can also append new lists to an existing nested list or add elements to the sublists themselves.

list_nest.append([40, 50, 60])
print(list_nest)

Output:

[[10, 25, 30], ['a', 'b', 'c'], [40, 50, 60]]

Iterating Over Nested Lists

Python makes it easy to iterate through nested lists using loops, which is particularly useful when working with matrices or complex datasets. You can loop through both the parent list and the nested lists inside.

for sublist in list_nest:
    for item in sublist:
        print(item, end=" ")

Output:

10 25 30 a b c 40 50 60 

Modifying Lists in Python

Static means that an object cannot be altered once it has been defined; whereas lists are arbitrary, which means that elements may be altered even after creation. Python offers ways on how to manipulate lists for example add elements, add list to another list, add / insert elements at particular positions, replace list, remove elements and delete list. Explored in detail below are each of these techniques:

Append the Lists

The append() method is used to add element to the list at the end of the list. This one alters the original list and is applied if the user must add only one item at a time.

city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.append('Bangalore')
print(city_list)

Output:

['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Bangalore']

Extend the List

In the case where you want to append a number of elements to a list at one time then you can use the extend() method. Unlike the append () which takes only one element adds it to the list while the extend () takes a parameter that is iterable like a list and adds each element in the parameter to the list.

num_list = [10, 20, 30, 40, 50, 60, 70, 80, 90]
num_list.extend([100, 110, 120, 130, 140, 150])
print(num_list)

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]

Change the Lists

To update a specific element in a list, you can assign a new value to the desired index. This method replaces the element at the specified position with a new one.

num_list[7]= 200
print(num_list)

Output:

[10, 20, 30, 40, 50, 60, 70, 200, 90, 100, 110, 120, 130, 140, 150]

Insert in the Lists

In the present example inserting an item in the list at a given position is done with the help of insert() method. It takes two arguments: The indices and value as which are associated with the insert method are the index where it will insert the element and the value to be inserted.

city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.insert(4,'Vadodara')
print(city_list)

Output:

['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Vadodara', 'Lucknow', 'Coimbatore']

Deleting Items From a List

You can delete elements from a list using the del keyword. This can remove a single element by its index or a slice of elements by specifying a range of indexes.

city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
del city_list[4]
print(city_list)

Output:

['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Coimbatore']
del city_list[4:6]
print(city_list)

Output:

['Agra', 'Chennai', 'Ahmedabad', 'Surat']

You can also delete the complete list using the below command:

del city_list

Emptying a List

In order to delete the contents of a list but leave the variable intact, a list is assigned an empty list. This is important when you want to remake the list, but the list still serves as a good frame.

city_list = ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list = []
print(city_list)

Output:

[]

Removing Specific Items with remove()

If you are aware of the value of the element which is to be removed but not its position, the remove() method is useful. It deletes the initial appearance of the value that is contained in its parameter.

city_list = ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.remove('Ahmedabad')
print(city_list)

Output:

['Agra', 'Chennai', 'Surat', 'Lucknow', 'Coimbatore']

Popping Items from a List

The pop() method removes and returns an element from the list, either from the end (if no index is provided) or from a specified index.

city_list = ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.pop(3)
print(city_list)

Output:

['Agra', 'Chennai', 'Ahmedabad', 'Lucknow', 'Coimbatore']

Python List Methods for Efficient Manipulation

Python offers several built-in methods to make list manipulation easier and more efficient. These methods allow you to perform various operations such as finding the length of a list, clearing its contents, reversing the order of elements, and sorting them. Let’s explore these methods in detail.

Finding the Length of a List

The len() function is used to determine how many elements are present in a list. This method is very useful when you need to know the size of a list, especially in loops and conditions.

city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
print(len(city_list))

Output:

6

Clearing a List

The clear() method is used to remove all elements from a list, effectively making it an empty list. It is a useful method when you want to reset a list without deleting the variable itself.

num_list = [1, 2, 2, 2, 3, 4, 5, 6, 6, 7, 6, 7]
num_list.clear()
print(num_list)

Output:

[]

Reversing a List

The reverse() method reverses the elements of a list in place, meaning it directly modifies the original list. This can be useful when the order of elements needs to be inverted.

city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.reverse()
print(city_list)

Output:

['Coimbatore', 'Lucknow', 'Surat', 'Ahmedabad', 'Chennai', 'Agra']

Sorting a List

The sort() method sorts the elements of a list in ascending order by default. You can also pass the reverse=True argument to sort the list in descending order. This method sorts elements in place, meaning it modifies the original list.

num_list=[1,2,2,2,3,4,5,6,6,7,6,7]
num_list.sort(reverse=True)
print(num_list)

Output:

[7, 7, 6, 6, 6, 5, 4, 3, 2, 2, 2, 1]

What is a Python Dictionary?

Dictionaries are mutable data types, unordered in nature, meaning they can be updated after they are created. Key and value pairs, and the keys must be unique. You can get a list of keys by calling a dictionary instance’s keys method. Syntactically they are written in a key, value pair format inside curly braces/curly brackets. We can update and delete the elements of the list of dictionaries. Dictionaries are implemented using hash tables.

{Key1:Value1,Key2:Value2,Key3:Value3,Key4:Value4}

Keys are always unique, and there cannot be any duplicates. There is no index in the dictionary, meaning they are not ordered. The key is the default iterator and is used to retrieve the value.

Syntax of Creating Dictionary With Examples

In Python, a dictionary is a collection of key-value pairs, allowing for efficient data retrieval and storage. Dictionaries can be created in several ways, each serving different needs. Here are four primary methods to create dictionaries in Python.

Creating an Empty Dictionary

An empty dictionary can be created using curly braces {} or the dict() function. This can be useful when you want to initialize a dictionary and populate it later.

dict_emp={}
print(dict_emp)

Output:

{}

Creating a Dictionary with Integer Keys

Dictionaries can have integer keys associated with their respective values. This is useful for storing data that requires numerical indexing.

dict_city={1: 'Ahmedabad', 2: 'Chennai', 3: 'Coimbatore',4:'Surat',5:'Agra'}
print(dict_city)

Output:

{1: 'Ahmedabad', 2: 'Chennai', 3: 'Coimbatore', 4: 'Surat', 5: 'Agra'}

Creating a Dictionary with String Keys

String keys are commonly used in dictionaries, especially when representing named entities or attributes.

dict_travel={'Country1':'USA', 'Country2': 'India', 'Country3':'Japan', 'Country4':'UK', 'Country5': 'Australia'}
print(dict_travel)

Output:

{'Country1': 'USA', 'Country2': 'India', 'Country3': 'Japan', 'Country4': 'UK', 'Country5': 'Australia'}

Creating a Dictionary with Mixed Keys and Values

Dictionaries can also contain a mix of different data types as keys and values, allowing for complex data structures.

mixed_dict= {'Country':'India', 1456:'Free','list':['city', 'road',12]}
print(mixed_dict)

Output:

{'Country': 'India', 1456: 'Free', 'list': ['city', 'road', 12]}

Finding the Length of a Python Dictionary

You can easily determine how many key-value pairs are in a dictionary using the len() function. This can help in checking if a dictionary is empty or how many items it contains.

dict_salesid = {'Sale1': 200, 'Sale2': 150, 'Sale3': 300, 'Sale4': 250, 'Sale5': 400}
print(len(dict_salesid))

Output:

5

Different Ways to Access Dictionary Elements

In Python, dictionaries are a versatile data structure that allows for efficient storage and retrieval of key-value pairs. Let’s explore various methods for accessing and manipulating dictionary elements.

Creating Dictionaries

First, let’s create two dictionaries to work with:

dict_salesid= {'SID1': Fiat
               'SID2': Mercedes
               'SID3': Maruti
               'SID4': Volkswagen
               'SID5': Kia}

dict_salesinfo= {'SID':Fiat,
                'Sales': 20000
                'LaunchDay':'Wed'
                'Cost': 500000}

Extracting Python Dictionary Elements Using Its Key

You can access the value associated with a key using the dictionary’s indexing method. Here’s how to extract the car name based on the sales ID:

sales_id='SID2'
if sales_id in dict_salesid:
    name= dict_salesid[sales_id]
    print('Sales ID is {}, Sales name is {}'. format(sales_id,name))
else:
    print('Sales ID {} not found'.format(sales_id))

Output:

Sales ID is SID2, Sales name is Mercedes

Setting Python Dictionary Element Using Its Key

You can also update existing keys or add new ones using the assignment operator. Here’s an example of modifying the LaunchDay and Cost in the dict_salesinfo dictionary:

dict_salesinfo['LaunchDay']='Thurs'
dict_salesinfo['Cost']=6000000
LaunchDay= dict_salesinfo.get('LaunchDay')
Cost=dict_salesinfo.get('Cost')
print('Launchday is {}, Cost is {}'. format(LaunchDay,Cost))

Output:

Launchday is Thurs, Cost is 6000000

Printing Dictionary Object Values in Key-Value Pair

To view all the values in a dictionary, you can use the values() method:

dict_values= dict_salesinfo.values()
print(dict_values)

Output:

dict_values(['Fiat', 20000, 'Wed', 500000])

Using the items() Function

The items() function returns a view object displaying a list of a dictionary’s key-value tuple pairs:

dict_items = dict_salesinfo.items()
print(dict_items)
print(type(dict_items))

Output:

dict_items([('SID', 'Fiat'), ('Sales', 20000), ('LaunchDay', 'Wed'), ('Cost', 500000)])
<class 'dict_items'>

Looping Through the items() Function

You can loop through the dictionary items using a for loop, which allows you to process each key-value pair easily:

for key, value in dict_salesinfo.items():
    print(key +"-"+str(value))

Output:

SID-Fiat
Sales-20000
LaunchDay-Wed
Cost-500000

Converting a Python List Into a Python Dictionary Object

A dictionary object contains key-value pairs, and the list must adhere to this format, or else it will throw an error.

sales_infolist=[['SID','Fiat'],['Sales','20000'],['LaunchDay','Wed'],['Cost','500000']]
print(type(sales_infolist))
sales_infolist_dict= dict(sales_infolist)
print(type(sales_infolist_dict))

Output:

<class 'list'>
<class 'dict'>

Copying a Python Dictionary Into a New Dictionary

When working with dictionaries in Python, you may often need to create a copy of an existing dictionary to manipulate or reference data without altering the original. Understanding how to copy a dictionary ensures data integrity while providing the flexibility to make changes as needed.

dict_salesinfo_new= dict_salesinfo.copy()
print(dict_salesinfo_new)

Output:

{'SID': 'Fiat', 'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000}

Updating the Python Dictionary Object

Updating a Python dictionary allows you to modify existing key-value pairs or add new ones, making it a versatile tool for managing dynamic data. This functionality is essential for maintaining accurate and up-to-date information in your applications, enabling efficient data handling and retrieval.

dict_salesinfo= {'SID':'Fiat','Sales': 20000,'LaunchDay':'Wed','Cost': 500000}
dict_salesinfo.update({'Profit':'50000'})
print(dict_salesinfo)

Output:

{'SID': 'Fiat', 'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000, 'Profit': '50000'}

How to Delete From Python Dictionary?

A dictionary object can be deleted entirely using the del statement, which frees up memory by removing the entire dictionary and its contents.

del dict_salesinfo

Output:

The dictionary object is deleted

Deleting a Specific Item From Python Dictionary

To delete a specific item from a dictionary, you can use the del statement along with the key of the item you want to remove, as shown below:

del dict_salesinfo['SID']
print(dict_salesinfo)

Output:

{'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000}

Another way to delete a specific item is by using the pop function.

print(dict_salesinfo.pop('SID'))

Output:

Fiat

Looping Through a Python Dictionary Object

Looping through a Python dictionary allows you to access each key-value pair efficiently, making it easy to process or manipulate data. This technique is essential for tasks such as data analysis, reporting, or any situation where you need to examine or modify the contents of a dictionary.

dict_keys= dict_salesinfo.keys()
print(dict_keys)
print(type(dict_keys))

Output:

dict_keys(['SID', 'Sales', 'LaunchDay', 'Cost'])
<class 'dict_keys'>
for var in dict_keys:
print(var + ":" + str(dict_salesinfo[var]))

Output:

SID:Fiat
Sales:20000
LaunchDay:Wed
Cost:500000

Conclusion

In Python, a list is a class of data structures that can store one or more objects or values. A list can store multiple items in one variable and be created using square brackets. Dictionaries are used to store data values in key:value pairs. A dictionary is an ordered, changeable collection, and does not allow duplicates. Elements of the dictionary are accessed through the keys.

Key Takeaways

  • Python Lists offer versatile ways to store ordered, mutable collections of items.
  • Python Dictionaries enable efficient key-value pair storage for quick lookups and modifications.
  • Indexing and Slicing allow flexible element access within lists.
  • Lists can be easily modified using methods like append(), insert(), and extend().
  • Dictionary methods like items(), keys(), and values() simplify working with key-value pairs.
  • Understanding nested lists and dictionary iterations can streamline complex data handling.
  • Lists and dictionaries are fundamental structures for efficient data manipulation in Python.

Frequently Asked Questions

Q1. Are lists and dictionaries the same in python 3?

A. The main difference is we can access items in a python dictionary and dictionary values via keys and not by their position. A list is an ordered sequence of objects, whereas dictionaries are unordered sets.

Q2. When to use dictionary vs list Python?

A. We can use a list and a dictionary depending on the problem statement. Lists are used to store data in an ordered and sequential pattern. In comparison, a dictionary is used to store large amounts of data for easy and quick access. A list is ordered and mutable, whereas dictionaries are unordered and mutable.

Q3. What are the different ways to store data in Python?

A. We can store data in multiple ways, like Lists, Tuples, and dictionaries.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Responses From Readers

Clear

spotifydownloader.co.za
spotifydownloader.co.za

Great insights on using lists and dictionaries in Python! I particularly liked the examples you provided; they really helped clarify the concepts. Looking forward to more posts like this!

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details