Collections in Python

Dikirimkan pada - Kali Terakhir Diubah Suai pada

Python is dynamically typed general purpose programming language. In this article I will present the most widely used methods and properties of the following Python collections:

  1. Lists 
  2. Dictionaries

The code samples which I present here are working under Python 3.x. If you'd like read more about the difference between Python 2.x and 3.x you can check the Python documentation here.

Lists

In Python, lists are the most widely used collections. Lists are very similar to arrays in other programming languages. Because Python is a dynamic programming language different types of data can be stored inside lists, like strings, numbers (integers, floats), other lists, tuples and dictionaries.

Lists can be created easily, by using square brackets, for example:

my_list_1 = [1, 3, 5, 7, 11, 13, 17]
my_list_2 = range(10, 21) # will result [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Above, my_list_1 is a list with seven items, my_list_2 is a list with eleven elements. I used the range() method from Python to populate the second list. This can be very handy when a normal sequence of numbers has to be generated or when iterating over a number of times is needed:

# the my_list_3 will have 10 items – from 0 to 9 – and
# it will cause the for loop to iterate 10 times and print
# the value in nr variable
my_list_3 = range(10)
for nr in my_list_3:
  print(nr)
  # and maybe do some other stuff

Operations on Lists

The main operations which are used on lists are indexing, appending, adding (using + operator), extending, inserting and pop-ing items.

Indexing is the basic method how lists can be manipulated:

# indexing - used for getting and setting values
a = [17, 19, 23, 29]
print(a[0]) # will print 17
print(a[2]) # will print 23
a[1] = 1001 # update the second item to 1001
print(a[1]) # will print 1001

The easiest way to add items to a list is using the append() method of the list:

my_list_4 = ["hello", 1, "world", "John", 2, 3, 4, 5, "Doe"]

my_list_4.append([6, 7, 8])   
# my_list_4 will be ["hello", 1, "world", "John", 2, 3, 4, 5, "Doe", [6, 7, 8]]

my_list_4.append("Australia") 
# my_list_4 will be ["hello", 1, "world", "John", 2, 3, 4, 5, "Doe", [6, 7, 8], "Australia"]

Lists can also be created by adding two lists (using the + operator), although, this is not an efficient way, if there is a possibility the extend() method should be used:

my_list_5 = [10, 100, 1000]
my_list_6 = ["ten", "hundred", "thousand"]

my_list_7 = my_list_5 + my_list_6 
# my_list_7 will be [10, 100, 1000, "ten", "hundred", "thousand"]

my_list_8 = [9, 8, 7]
my_list_9 = [6, 5, 4, 3, 2, 1]

my_list_8.extend(my_list_9) 
# my_list_8 will be [9, 8, 7, 6, 5, 4, 3, 2, 1]

There are cases when a list needs to be extended, but the item needs to be added to a specific position within the list, then the insert() method should be used:

my_list = [2, 5, 6, 7]
my_list.insert(0, 1) # will insert the 1 at the 0th position
my_list.insert(2, 3) # will insert the 3 at the 2nd position
my_list.insert(3, 4) # will insert the 4 at the 3th position

In case an item should be removed from the list, the pop() and the remove() methods can help:

# pop - removes(pops out) the last item in the list
my_list = [1, 2, 3]
my_list.pop()  # will remove and return the value 3
print(my_list) # will display [1, 2]

# remove - removes ONLY the first the value passed in as parameter from the list
my_list = [4, 5, 6, 7, 4, 6]
my_list.remove(6) # will only remove the 6 on the 2nd position
print(my_list)    # will display [4, 5, 7, 4, 6]

Items can be removed from lists using the del keyword:

# del - deleting an item from the list
c = [55, 75, 85, 105]
del c[2] # will delete the list item on 2nd position
print(c) # will display [55, 75, 105]

The length of list can be determined using the len() method, lists can be sorted using the sort() method, the reverse() method helps to reverse the order of items in a list:

# len, sort and reverse methods
print(len(my_list))  # will print 5
my_list.sort()
print(my_list)       # will display [4, 4, 5, 6, 7]
my_list.reverse()
print(my_list)       # will display [7, 6, 5, 4, 4]

Lists in python are very flexible and can be used as different type of data structures, like stack (LIFO) – using the append() and pop() methods – or queues(FIFO) – using the insert() and pop() methods.

Dictionaries

Dictionaries are key-value pairs in Python -- in other programming languages these can be called associative arrays. Dictionaries are indexed by keys. The dictionary type in Python is special because these are marked exactly the same way as objects in standard JSON format, { “key1”: “value1”, “key2”:value2, “key3”:”value3”}. The MongoDB Python API – pymongo – uses dictionaries when returning values and saving to the database.

Operations on Dictionaries

#creating a new dictionary with 3 keys : name, age and balance
d = { "name": "John Doe", "age": 44, "balance": 235.5 }

#printing out the values of the dictionary using the kyes
print(d["name"])    # will display "John Doe"
print(d["age"])     # will display 44
print(d["balance"]) # will display 235.5

Dictionaries can be created in a variety of ways using the dict() method:

# using dict to create dictionaries
my_dict_1 = dict(name="John Doe", age=44, balance=235.5)
my_dict_2 = dict({ "name": "John Doe", "age": 44, "balance": 235.5 })
my_dict_3 = dict(zip(["name", "age", "balance"], ["John Doe", 44, 235.5]))
print(my_dict_1) # will print {'age': 44, 'name': 'John Doe', 'balance': 235.5}
print(my_dict_2) # will print {'age': 44, 'name': 'John Doe', 'balance': 235.5}
print(my_dict_3) # will print {'age': 44, 'name': 'John Doe', 'balance': 235.5}

# comparing the three dictionaries shows 
# these have the same keys and values
print(my_dict_3 == my_dict_2 == my_dict_1) # will print true

The elements in a dictionary can be accessed using multiple methods, with indexing as seen above, and also with for loops:

# using a for loop to print out values
for key, val in enumerate(d):
  print("{} = {}".format(key,val))

# the dictionary has a method called items() 
# which does basically the same
for key, val in d.items():
  print("{} = {}".format(key,val))

The values within a dictionary can be read and updated in the same way as in a list, using the index operator. The dictionary also has the get() method for accessing data and the update() method to change the data:

# index, get and update methods
my_dict_1 = dict(name="John Doe", age=44, balance=235.5)
print(my_dict_1["name"])     # will print "John Doe"
print(my_dict_1.get("name")) # will print "John Doe"

# specifying a value for a non-existing key will add the
# key-value pair to the dictionary
my_dict_1["website"] = "http://example.com"
print(my_dict_1)  
# will print {'age': 44, 'name': 'Jane Doe', 'website':'http://example.com', 'balance': 235.5}

# using the update method with one named parameter
my_dict_1.update(name = "Jane Doe")
print(my_dict_1) 
 # will print {'age': 44, 'name': 'Jane Doe', 'website':'http://example.com', 'balance': 235.5}

# update can take a dictionary as parameter and will map the keys
my_dict_1.update({"name" = "Jane Doe", "balance" = 500})
print(my_dict_1)  
# will print {'age': 44, 'name': 'Jane Doe', 'website':'http://example.com', 'balance': 500}

Dictionaries have length (the same way as lists have), this can be calculated using the len() method. Sorting, reversing does not make sense in case of dictionaries, so these are not available in Python.

The code is hosted on GitHub as gist, here are the links:
Code for Lists: https://gist.github.com/gergob/058c5ad42f04e7169679
Code for Dictionaries: https://gist.github.com/gergob/010d80edd977ba2ea51a

 

Dipaparkan 16 Disember, 2014

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Artikel Seterusnya

New Profile Rating Feature Boosts Award Rate