Data Structures in Python-Introduction

In the previous section of Mastering Python for Blockchain series, we read about the Data Structures in Python-Lists. This article will focus on the Data Structures in Python-Dictionaries. We will learn about creating a simple dictionary, functions used on dictionaries, iterations in dictionaries.  If you have not read the previous articles of Mastering Python for Blockchain Series, please do read them. It will help you build your Python foundation from the beginning. Start from here.

Few quick words: I will suggest you to download the latest version of Python which will help you to practice coding python programs. In case you do not have Python installed in your system you can use this link to online run your Python codes.

I also suggest you to visit the article here to learn the basic concepts of Blockchain.

Data Structures in Python-Dictionaries-Definition

  • Dictionaries, like Lists, are a set of zero or more elements, separated by commas and enclosed by curly brackets ({ }).
  • They differ from Lists, such that the order of items in Dictionaries, does not matter. In addition, each item is represented by a key, rather than an offset (0, 1, 2, …so on as in Lists).
  • The key can be any of the Python’s immutable data types-Booleans, integers, floats, strings, tuples, and some others that you will learn about in later parts of this Mastering Python for Blockchain series.
  • Syntax: {key1: item1, key2 : item2, key3 : item3,…..so on}
  • Empty Dictionary: { }
  • Dictionaries are mutable. Hence you can add, delete or change any of its keys-items.

Note: Some other languages might call Dictionaries as Associative Arrays, or Hashes or Hashmaps.

Creating a simple Dictionary

Here the keys are 1stline and 2ndline.

dict( ) function to create Dictionaries

  • For some people, typing curly braces ({ }) and multiple quotes (” “) is a pain.
  • They can use the dict( ) function, which creates dictionaries.
  • Let us consider the previous example, where we created a simple dictionary. Let us now create it using the dict( ) function.

Output:

One of the limitations in this method is that the key should be a legal variable name (no spaces, no reserved words)

So if we give spaces like below, Python gives error.

dict( ) function to convert two-value sequences into a dictionary

  • We can use the dict( ) function to convert any sequence (tuples, lists) of two-valued items into a dictionary.
  • The first element of the items become the keys and the second elements become the values.
  • Converting a list of two-valued lists into a dictionary

Output:

  • Converting a list of two-valued tuples into a dictionary

Output:

  • Converting a tuple of two-valued tuples into a dictionary

Output:

  • Converting a tuple of two-valued lists into a dictionary

Output:

  • Converting a tuple of two-character strings into a dictionary

Output:

  • Converting a list of two-character strings into a dictionary

Output:

Add or Change an item in a dictionary by key

  • We read about adding and modifying elements/items in a list using insert ( ), append ( ) and offsets. Please revisit here if required.
  • Adding and modifying elements in a dictionary is much simpler.
  • Simply use the key. If you introduce a new key, the element is added in the end of the dictionary. If the key is present in the given dictionary, then it will modify the value of the key.

Output:

Let us now try and add Elizabeth Taylor in the end of the dictionary. We can introduce a new key ‘h5’ to do so. See below.

Output:

Now if we simply want to change or modify an existing value, then we can assign the new value to the respective key. For instance, let’s change Kate Winslet to Grace Kelly. In that case we can assign the new value ‘Grace Kelly’ to ‘h2’. See below.

Ouput:

Note: Keys in Dictionaries are unique. If you use a key more than once in a dictionary, then the last key (rightmost) wins.

Output:

Get an item/element by using the key or the get( ) function

  • By specifying the dictionary and the key you get the respective item/element.
    Syntax: dictionary_name[key]

Output:

barry

  • Now if the key is not in the dictionary, Python will give you an exception.

Output:

  • In order to avoid any exceptions, you can find beforehand whether a key is present in the dictionary or not. For this we can use in
    Syntax: key in dictionary_name

Output:

False

  • We can also use the get( ) function.
    Syntax: dictionary_name.get(key)
    For the dictionary dict defined above, we can also fetch the item at the key ‘lees’ by using the get( ) function. See below.
This image has an empty alt attribute; its file name is image-29.png

Output:

barry

  • Now we saw that if a key is not present in the dictionary then using dictionary_name[key] will give an error. But in the case of the get( ) function, we get ‘None’. See below.

Output:

None

  • And if we specify an optional value, Python will give that value as the output. See below.

Output:

keys( ) function to get all the keys of a dictionary

  • We can get all the keys of a dictionary using the keys( ) function.
    Syntax: dictionary_name.keys( )

Output:

Note: If we would have used Python 2, it would have returned a list of all the keys. Python 3 (which we are using), returns dict_keys, which is an iterable view of the keys. This is because Python 3 does not spend the time and resources to create a list which you might not use. You can convert it to a list (suppose you wanted to get a list of all the surnames), by calling the list( ) function.

Output:

values( ) function to get all the values in a dictionary

Syntax: dictionary_name.values( )

Output:

items( ) function to get all the key-value pairs in a dictionary

Syntax: dictionary_name.items( )

Output:

len( ) function to get the length of a dictionary

Syntax: len(dictionary_name)

Output:

3

Combine dictionaries with {**a,**b}

  • You can combine two or more dictionaries using the ** unicorn glitter.

Output:

Now let us define another dictionary ‘new’ and then merge it to ‘a’ and ‘b’.

Output:

update( ) function: copy one dictionary to another dictionary

  • We can copy the keys : values from one dictionary into another dictionary using the update( ) function.
  • Suppose we need to copy dictionary1 to dictionary2. Then the syntax will be as below
    Syntax: dictionary2.update(dictionary1)

Output:

  • Now what will happen if a key is repeated. In that case the value of the last key (rightmost) wins.
  • Let’s say we add khan:salman in the heroes_b dictionary defined above. Then we have khan (key) which is repeated. Let us see what happens when we copy the elements of heroes_b into heroes.

Output:

We see that Python only takes khan:salman (rightmost) and removes khan:sharukh.

del: Delete an item of a dictionary by key

  • We can delete an item of a dictionary using del.
  • Syntax: del dictionary_name[key]
  • Suppose we wanted to remove kumar:akshay from our updated dictionary heroes discussed above.

Output:

pop( ): get an item by key and delete it

  • The pop( ) function combines get( ) function and del.
  • If you give pop( ) function a key and the key exists in the dictionary, then the pop( ) function will return the matching value and deletes it. If the key doesn’t exist, Python gives an exception.
  • Syntax: dictionary_name.pop[key]

Output:

Let us see if the k3:v3 is deleted or not.

Output:

Lets see what happens when the key is not present.

Output:

If we give a second default argument to pop( ), then the default value is returned and nothing is changed in the dictionary

Output:

clear( ): delete all items of a dictionary

  • To delete all the items from a dictionary, use the clear( ) function. Or simply assign an empty dictionary to the name.
  • Syntax: dictionary_name.clear( )

Output:

Or,

Output:

Check for a key with in

  • We can check whether a key is contained in a dictionary or not, using in
  • In the below example, we have defined a dictionary ‘heroes’. Then we check whether the key ‘Roberts’ exists in the dictionary or not.

Output:

Now let us see whether the key ‘Cruise’ exists in the dictionary or not.

Output:

Assign with =

  • Like lists, if you assign different names to a dictionary, then any change in the dictionary will be reflected in all the names that refer to it.
  • Let us see an example below

Output:

So you can see that as we add a new key:value to the dictionary ‘heroes’, it gets added to the dictionary, ‘heroes’.

Let us see whether the dictionary ‘heroes_hollywood’, changes or not.

Output:

Yes it also changes.

Copy with copy( )

  • In the previous section, we saw that we can use = to assign a different name to a dictionary. When the dictionary changes, all the names assigned to the dictionary will change.
  • For instance in the previous example, the dictionary of Hollywood stars was given the name ‘heroes’ and ‘heroes_hollywood’, by using =

If we want to create a new dictionary all together by copying the items of another dictionary, such that changes in one do not affect another, then we can use the copy( ) function.

Let us see an example.

Let’s see whether Ven Diesel is added to the Dictionary heroes or not.

Output:

So yes, Ven Diesel is added to heroes.

Let us see whether it is added to the dictionary ‘action_heroes’ or not.

Output:

So, we see that Ven Diesel is not added to the dictionary ‘action_heroes’. This means changes in dictionary ‘heroes’ does not impact ‘action_heroes’.

Copy with deepcopy( )

  • Suppose we have a list as one of the values in a dictionary.
  • We create another dictionary using the copy( ) function. See the example given below for a dictionary which lists the cryptocurrencies owned by different people. The key ‘Eliot’ has a list [‘Bitcoin’,’Ether’] as its value.
  • Output:
  • In this case of using the copy( ) function, we know that when the value of any key is changed in one dictionary it is not changed in the other dictionary. See below.
  • Output:
  • But if we change an element of the list in ‘crypto’, the change is well reflected in the other dictionary ‘crypto_copy’ also.

Output:

  • So in those cases where lists are involved and you do not want to change all the dictionaries you have copied, use deepcopy( )

Output:

Comparison of Dictionaries

  • Dictionaries are compared using the == and != operators.

Output:

  • The order of the key:value pair does not matter.

Output:

  • Other operators like >=, <= do not hold valid for dictionaries.

Output:

Iterate with for and in || keys( ), values( ), items( )

  • Iterating over the keys in a dictionary using the key() function returns the key values in the dictionary. And iterating over the values of a dictionary using the value( ) function, returns the values.

Output:

Now let us iterate over the values

Output:

  • You can get the keys and values at the same time using the items( ) function. It will come as Tuples.

Output:

  • We can even assign two values to the Tuple in one step. Assign the first value (key) to investors and the second value (values) to cryptocurrencies.

Output:

Leave a Reply