Sunday, August 23, 2015

Python Basics - 016: Dictionaries

Previous chapter: Exception Handling



Python Basics - 016: Dictionaries and Sets

Let's see some complex data types

Dictionary

Dictionary is a data type which is a list of key-value pairs. It is very similar to Lists or arrays, instead of index values we will use some arbitrary value which can be any object like a number or a string.

Dictionaries can be initiated using the following syntax:


employeePosition = {
    "Alan": "Sr Developer",
    "John": "Quality Analyst",
    "Jack": "Delivery Manager"
}

Here the names are the keys and the positions are the values, there are many other ways to initiate a dictionary[1], but we'll stick to one syntax to make it more consistent.

Similar to a list or a tuple, dictionary's values can be accessed using the square bracket and passing the key value in the place of the index.


print("Alan is a", employeePosition["Alan"])

If we want to add a new employee to the mix, the syntax is very simple, just assign the value by using the key. If they key is not already available in the dictionary it will be added, if the key is present then it's value will be overwritten.


employeePosition["Julie"] = "Sales Professional"

Similar to object member variables, we can remove key-pairs from the dictionary using the del keyword[2]


del employeePosition["John"]

Let's check if he's really removed from the dictionary by looping over the dictionary:


for name, position in employeePosition.items():
    print(name, "is a", position);

The output will be:


Jack is a Delivery Manager
Julie is a Sales Professional
Alan is a Sr Developer

As we can see, John has been removed from the dictionary.

Unlike lists, dictionaries are easier to use when dealing with different kind of data, it is easier to access random values without iterating because the keys are distinct.

Dictionaries do not preserve any sort of order while storing your data, so while looping do not expect it to be in the order you inserted or any other order for that matter.

Sets and Frozensets

Sets are a list of objects that are distinct and hashable. Hashable objects are usually immutable built-in python data types, which means dictionaries and lists cannot be in a set. Objects which are instances of user defined classes can be used in a set as they are all hashable.

Sets also implement the operations available in mathematical set theory such as union, intersection, subset, superset, difference and symmetric difference.

While set is mutable, frozenset is immutable other than that they share all behaviour and functions.

Sets can be created using the {} syntax:


oscars = {"Jennifer", "Matthew", "Ellen", "Jack", "Leonardo", "Jack"}

As you can see Jack is repeated twice, but when you try to print the set, there will be only one instance of the name, set will automatically remove duplicates.


print("Stars at the oscars:",oscars);

output:


Stars at the oscars: {'Jack', 'Ellen', 'Matthew', 'Jennifer', 'Leonardo'}

We can also see that sets doesn't keep the order of elements according to the order of inserts of any other order, just like dictionaries.

To create an immutable set, we need to create a frozenset. Here's how:


afterparty = frozenset(["Jennifer", "Neil", "Woody", "Leonardo", "Rachel"])

Sets and frozen sets are easy to work with when having to check for presence or to do some set theory based operation. Here are some examples:


# to check if Jennifer went to the oscars

print("was Jennifer in the oscars?", "Jennifer" in oscars)

# to perform difference operation, to find who went to oscars but not the after party

print("Stars who came only to the oscars:", oscars - afterparty)

# to perform intersection operation i.e to find out who went to both oscars and the after party

print("Stars who attended both oscars and the after-party:", oscars & afterparty)

# to perform union operation, bring out all distinct values from both sets

print("All stars who were seen:", oscars | afterparty)

The output:


was Jennifer in the oscars? True
Stars who came only to the oscars: {'Jack', 'Ellen', 'Matthew'}
Stars who attended both oscars and the after-party: {'Jennifer', 'Leonardo'}
All stars who were seen: {'Jennifer', 'Rachel', 'Leonardo', 'Neil', 'Matthew', 'Ellen', 'Woody', 'Jack'}

Sets are a great way to group objects and to get distinct list of items.



We're actually at the end of the beginner's tutorial, I can't believe I've typed up so much stuff! This pretty much covers all the core functionality of python3 but this in itself is not sufficient for any real life projects.

Let's move on to a real life but a very tiny project. We will have to use libraries and modules such as url lib, sys, os etc., We will cover all of that as part of the next intermediate tutorial.

Let me come up with a project idea and I will post a comprehensive tutorial. Till then, happy coding!

I've posted all the code used in this tutorial in github

The tutorial content itself is available in bitbucket


References:

  1. https://docs.python.org/3.4/library/stdtypes.html#mapping-types-dict
  2. https://docs.python.org/3.4/tutorial/datastructures.html#the-del-statement
  3. http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python
  4. https://docs.python.org/3.4/library/stdtypes.html#set-types-set-frozenset
  5. https://docs.python.org/3.4/tutorial/datastructures.html#sets



Previous chapter: Exception Handling

No comments:

Post a Comment