For clarification, we describe how Python Dict use Index and other 5 operations, and how different Python List operations are. Essentially, these 2 data types are often used in Python programming.
All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.
Estimated reading time: 7 minutes
EXPLORE THIS ARTICLE
TABLE OF CONTENTS
BONUS
Source Code Download
We have released it under the MIT license, so feel free to use it in your own project or your school homework.
Download Guideline
- Prepare Python environment for Windows by clicking Python Downloads, or search a Python setup pack for Linux.
- The pack of Windows version also contains pip install for you to obtain more Python libraries in the future.
OPERATION 1
Dict & List Init
First, you can see what operations for Python Dict and List should be listed. After that, it is shown that sample data operated through out this example are sequentially in relationship with data of previous steps.
Basic Operations
Let us demonstrate operations Init, Add, Index, Update, Delete, and Count on Python List and Dict objects by the following sample data that will progress forward step by step with significant changes. In subsquent sections, we will explain these data for each operation by one or more methods if any alternative exists.
C:\>python features.py
*** Initial LIST
['a', 'b', 'c']
*** Initial DICT
{'ax': 'a', 'bx': 'b', 'cx': 'c'}
*** Append LIST
['a', 'b', 'c', 'd', 5]
*** Append DICT
{'ax': 'a', 'bx': 'b', 'cx': 'c', 'dx': 'd', 9: 7}
*** Index of LIST
list_1[0] = a
list_1[4] = 5
*** Index of DICT
dict_1['ax'] = a
dict_1[9] = 7
*** Update LIST
['a', 'bb', 'c', 'd', 25]
*** Update DICT
{'ax': 'a', 'bx': 'bb', 'cx': 'c', 'dx': 'd', 9: 27}
*** Delete LIST by index
list_1[3] = d is deleted
['a', 'bb', 'c', 25]
*** Delete DICT by index
dict_1['f1'] is None
dict_1['dx'] = d is deleted
{'ax': 'a', 'bx': 'bb', 'cx': 'c', 9: 27}
dict_1[9] is deleted
{'ax': 'a', 'bx': 'bb', 'cx': 'c'}
*** Delete LIST by value
list_1['c'] is deleted
['a', 'bb', 25]
*** Count the number of LIST
LIST number is 3
*** Count the number of DICT
DICT number is 3
1. INIT
The function list()
or the expression list_1 = []
create List objects containing data separated by commas and brackets. While in a different way, dict()
initializes Dict objects with commas, colon, and braces. The data in List or Dict can be integer or string.
# 1. Initial
list_1 = list(["a", "b", "c"])
print("*** Initial LIST")
print(list_1)
dict_1 = dict({"ax": "a", "bx": "b", "cx": "c"})
print("\n*** Initial DICT")
print(dict_1)
*** Initial LIST
['a', 'b', 'c']
*** Initial DICT
{'ax': 'a', 'bx': 'b', 'cx': 'c'}
OPERATION 2
Dict & List Add
For Python Dict or List, It is necessary to append a data item at its end pointed by an index. Thus it can retain imcoming information structuredly.
2. ADD
The method list_1.append()
can add a data item to the end of List objects. Here add an one-character string and an integer, and both of them have implied indexes, 3 and 4, respectively.
For Python Dict objects, the expression dict_1["dx"] = "d"
has done data appending to the end by specifying a pair of index and value. Notice that index can be string type, rather than only integer type. It is different from that in List objects.
# 2. Append
list_1.append("d")
list_1.append(5)
print("\n*** Append LIST")
print(list_1)
dict_1["dx"] = "d"
dict_1[9] = 7
print("\n*** Append DICT")
print(dict_1)
*** Append LIST
['a', 'b', 'c', 'd', 5]
*** Append DICT
{'ax': 'a', 'bx': 'b', 'cx': 'c', 'dx': 'd', 9: 7}
OPERATION 3
Dict & List Index
Python Dict and List are addressing data items by pairs of index and value. Alternatively, List can alter indexes by using list.insert() to insert items in middle, rather than at end.
3. INDEX
Python List objects consist of sequential items with implied indexes counting from zero.
Python Dict objects use enumerated keys as indexes, that is, keys should be indicated, not implied, and any key could be of string or integer type.
# 3. Index
print("\n*** Index of LIST")
print("list_1[0] = "+list_1[0])
print("list_1[4] = "+str(list_1[4]))
print("\n*** Index of DICT")
print("dict_1['ax'] = "+dict_1["ax"])
print("dict_1[9] = "+str(dict_1[9]))
*** Index of LIST
list_1[0] = a
list_1[4] = 5
*** Index of DICT
dict_1['ax'] = a
dict_1[9] = 7
OPERATION 4
Dict & List Update
In Python Dict or List, you should specify an index for the item to be updated.
4. UPDATE
You can update List and Dict objects in a similar way that locates items by keys, and then change the value of that item. Note that List objects are indexing from zero.
# 4. Update
print("\n*** Update LIST")
list_1[1] = "bb";
list_1[4] = 25;
print(list_1)
print("\n*** Update DICT")
dict_1["bx"] = "bb";
dict_1[9] = 27;
print(dict_1)
*** Update LIST
['a', 'bb', 'c', 'd', 25]
*** Update DICT
{'ax': 'a', 'bx': 'bb', 'cx': 'c', 'dx': 'd', 9: 27}
OPERATION 5
Dict & List Delete
Python Dict allow users to remove an item by a specific index, while, in particular, Python List has an extra capability of finding an item to be deleted only by value.
5.1 DELETE BY INDEX
For List objects, just specify the key less than the size of a List object, you will delele an item without out of range messages. All items in that List object will be re-indexing automatically.
For Dict objects, it is necessary to handle exceptions during deletion. The method dict_1.pop("f1", None)
has one more parameter for the purpose of returning None
if items are not found.
# 5.1 Delete by index
print("\n*** Delete LIST by index")
val = list_1.pop(3)
print("list_1[3] = "+val+" is deleted")
print(list_1)
print("\n*** Delete DICT by index")
val = dict_1.pop("f1", None)
if (val == None) :
print("dict_1['f1'] is None")
val = dict_1.pop("dx", None)
print("dict_1['dx'] = "+val+" is deleted")
print(dict_1)
print("dict_1[9] is deleted")
del dict_1[9]
print(dict_1)
*** Delete LIST by index
list_1[3] = d is deleted
['a', 'bb', 'c', 25]
*** Delete DICT by index
dict_1['f1'] is None
dict_1['dx'] = d is deleted
{'ax': 'a', 'bx': 'bb', 'cx': 'c', 9: 27}
dict_1[9] is deleted
{'ax': 'a', 'bx': 'bb', 'cx': 'c'}
5.2 DELETE BY VALUE
List objects have a powerful function of deletion by value, while Dict objects don’t have.
If you are going to remove a certain item in the middle of a List object, you don’t have to search for that through all items out, but just specify the data value you want to delete. The expression is like list_1.remove("c")
.
# 5.2 Delete by value
print("\n*** Delete LIST by value")
list_1.remove("c")
print("list_1['c'] is deleted")
print(list_1)
*** Delete LIST by value
list_1['c'] is deleted
['a', 'bb', 25]
OPERATION 6
Dict & List Count
Length or count operation for a whole item list is usually helpful, as index should be less than that. The counting function for Python Dict is like that for List.
6. COUNT
For both List and Dict objects, you can use the same method len()
to calculate their numbers just like len(list_1)
or len(dict_1)
. As tutorials have progressed so far, the example List object becomes ['a', 'bb', 25]
, and Dict object is {'ax': 'a', 'bx': 'bb', 'cx': 'c'}
. Therefore the counting numbers are both equal to 3.
# 6. Count
print("\n*** Count the number of LIST")
print("LIST number is "+str(len(list_1)))
print("\n*** Count the number of DICT")
print("DICT number is "+str(len(dict_1)))
*** Count the number of LIST
LIST number is 3
*** Count the number of DICT
DICT number is 3
FINAL
Conclusion
You can refer this article to be a memo during Python programming, because it will remind what to write when you encounter ambiguity. Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!