Skip to main content

Tutorial 2 - Dictionaries

Dictionaries in Python

Dictionaries

The following content and the code excerpts have been derived from the following sources:
  1. Dictionaries, LearnPython.org. https://www.learnpython.org/en/Dictionaries
  2. Merging two Dictionaries. https://www.geeksforgeeks.org/python-merging-two-dictionaries/
  3. How to Loop a Dictionary. https://www.mkyong.com/python/python-how-to-loop-a-dictionary/
  4. Dictionary methods in Python. https://www.geeksforgeeks.org/dictionary-methods-in-python-set-1-cmp-len-items/
"A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it."
A dictionary can be identified using curly braces.

Creating Dictionaries

In [7]:
phonebook = {} #empty dictionary is defined

#adding elements using keys and values
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
print(type(phonebook))
{'Jill': 947662781, 'John': 938477566, 'Jack': 938377264}
<type 'dict'>
In [6]:
#dictionary can be defined as follows too
phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}
print(phonebook)
print(type(phonebook))
{'Jill': 947662781, 'John': 938477566, 'Jack': 938377264}
<type 'dict'>

Accessing, Modifying and Deleting items in a Dictionary

Accessing items in a Dictionary

Dictionaries use the keys in the key-value pairs to access its elements. We can use the functions items() to access the items in a ditionary.
Syntax: dictionary.items()
In [9]:
print(phonebook['John']) #prints the value associated with the key 'John' in the dictionary phonebook
938477566
In [20]:
#We can iterate over the items in a dictionary using loops
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))
    
print (phonebook.items()) #gives the list of key-value pairs
Phone number of Jill is 938118406
Phone number of John is 938477566
Phone number of Jack is 938377264
[('Jill', 938118406), ('John', 938477566), ('Jack', 938377264)]

Modifying items in a Dictionary

We can use the update() function to modify an item in the dictionary or simply use the = operator.
In [25]:
phonebook.update({'Jill': 938118406}) #assigns new value to the item with the key 'Jill' using update() function
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))
Phone number of Jill is 938118406
Phone number of John is 938477566
Phone number of Jack is 938377264
In [24]:
phonebook['Jill'] = 845126794 #assigns new value to the item with the key 'Jill' using = operator
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))
Phone number of Jill is 845126794
Phone number of John is 938477566
Phone number of Jack is 938377264

Deleting Items in a Dictionary

We can use the del() function or the pop() function to delete items from a Dictionary
In [26]:
del phonebook["John"]
print(phonebook)
{'Jill': 938118406, 'Jack': 938377264}
In [27]:
phonebook.pop("John") #throws error because the key 'John' does not exist in the dictionary object phonebook anymore
print(phonebook)

KeyErrorTraceback (most recent call last)
<ipython-input-27-57c34b29c14f> in <module>()
----> 1 phonebook.pop("John")
      2 print(phonebook)

KeyError: 'John'
In [28]:
phonebook.pop("Jill")
print(phonebook)
{'Jack': 938377264}

Merging two dictionaries

There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Python. In this article, we will discuss few ways of merging dictionaries.

Using the method update()

By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None.
In [58]:
def Merge(dict1, dict2): 
    return(dict2.update(dict1)) 
     
# Driver code 
dict1 = {'a': 10, 'b': 8} 
dict2 = {'d': 6, 'c': 4}
dict3 = {'e': 2, 'f': 0}
  
Merge(dict1, dict2)
  
# changes made in dict2 
print(dict2) 
{'a': 10, 'c': 4, 'b': 8, 'd': 6}
{'a': 10, 'c': 4, 'b': 8, 'e': 2, 'd': 6, 'f': 0}

Using ** in Python (WORKS in python 3.5 or higher)

This is generally considered a trick in Python where a single expression is used to merge two dictionaries and stored in a third dictionary. The single expression is . This does not affect the other two dictionaries. implies that the argument is a dictionary. Using [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.
In [31]:
def Merge(dict1, dict2): 
    res = {** dict1, ** dict2} 
    return res 
      
# Driver code 
dict1 = {'a': 10, 'b': 8} 
dict2 = {'d': 6, 'c': 4} 
dict3 = Merge(dict1, dict2) 
print(dict3) 
  File "<ipython-input-31-30f023967657>", line 2
    res = {** dict1, ** dict2}
            ^
SyntaxError: invalid syntax

Dictionary and Looping

Looping over Keys and Values using items

In [35]:
stocks = {
        'IBM': 146.48,
        'MSFT':44.11,
        'CSCO':25.54
    }
    
#looping over the keys (when only one variable is used, here c, it can be understood as refering to the keys)
for c in stocks:
    print(c)
CSCO
IBM
MSFT
In [36]:
for k, v in stocks.items(): #when 2 varaibles are used the first one identifies keys and the second identifies values
    print(k,v)
('CSCO', 25.54)
('IBM', 146.48)
('MSFT', 44.11)
In [43]:
for k, v in stocks.items():
    print("Code : {0}, Value : {1}".format(k, v)) #Another Way to use the keys and values when printing
    
for k, v in stocks.items():
    print("Value : {0}, Code : {1}".format(v, k))
    
for k, v in stocks.items():
    print("Code : {1}, Value : {0}".format(v, k))
    
Code : CSCO, Value : 25.54
Code : IBM, Value : 146.48
Code : MSFT, Value : 44.11
Value : 25.54, Code : CSCO
Value : 146.48, Code : IBM
Value : 44.11, Code : MSFT
Code : CSCO, Value : 25.54
Code : IBM, Value : 146.48
Code : MSFT, Value : 44.11

Looping Over Key and values without using Items

In [47]:
d = {"first_name": "Alfred", "last_name":"Hitchcock"}

for k in d:
    print("{} = {}".format(k, d[k]))
first_name = Alfred
last_name = Hitchcock

Popular posts from this blog

Tutorial 6 - Statistics and Probability

Statistics and Probability with Python HW 6 Statistics and probability homework ¶ Complete homework notebook in a homework directory with your name and zip up the homework directory and submit it to our class blackboard/elearn site. Complete all the parts 6.1 to 6.5 for score of 3. Investigate plotting, linearegression, or complex matrix manipulation to get a score of 4 or cover two additional investigations for a score of 5. 6.1 Coin flipping ¶ 6.1.1 ¶ Write a function, flip_sum, which generates $n$ random coin flips from a fair coin and then returns the number of heads. A fair coin is defined to be a coin where $P($heads$)=\frac{1}{2}$ The output type should be a numpy integer, hint: use random.rand() In [4]: import numpy as np import random """def random_flip(): return random.choice(["H", "T"]) def flip_sum(n): heads_count = 0 ...

Tutorial 5 - Matplotlib

Matplotlib Tutorial In [13]: % matplotlib inline import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # Setting some Pandas options pd . set_option ( 'display.notebook_repr_html' , False ) pd . set_option ( 'display.max_columns' , 25 ) pd . set_option ( 'display.max_rows' , 25 ) Homework 4 ¶ Couple of reference site: http://matplotlib.org/examples/pylab_examples/ http://docs.scipy.org/doc/numpy/ Homework 4.1 ¶ 4.1.a Create a figure with two subplots in a row. One shows a sine wave of x from with x = 0 ... 2*pi the other shows the tagent of x with the same range. Label the figures. Should look something like: We can follow the following steps to get the required graphs showing sine and tangents of x: Create a numpy array x with values from 0 to 2*pi with 0.001 as step value Set the height and w...

Domain Research - Stock Market Prediction

Hi, as part of my research on a domain of Big Data implementation, I chose Stock Market Prediction. Here I present to you the things that I have learned during my research in the domain. Can stock market be predicted? Early researches on stock market prediction revolved around whether it could be predicted. One of such researches suggested that “short term stock price movements were governed by the  random walk hypothesis  and thus were unpredictable”. Another stated that “the stock price reflected completed market information and the market behaved efficiently so that instantaneous price corrections to equilibrium would make stock prediction useless.” In simple terms, the researches inferred that since the market was affected by a lot of factors which were random predicting the stock market is almost impossible. However, researches carried out later (Brown & Jennings 1998; Abarbanel & Bushee 1998) made use of ...