Dictionaries

Dictionaries are similar to lists, but instead of being indexed by integers they are indexed by keys.

In [2]:
grades = {'John Smith':75, 'Alice Brown':93, 'Walter White': 68}
In [3]:
print(grades)
{'John Smith': 75, 'Alice Brown': 93, 'Walter White': 68}

Dictionary values can be accessed using their keys:

In [4]:
grades['Walter White']
Out[4]:
68
In [5]:
grades['Walter White'] = 95
In [6]:
print(grades)
{'John Smith': 75, 'Alice Brown': 93, 'Walter White': 95}

Assigning to a key which is not in a dictionary adds that key to the dictionary:

In [9]:
grades['Albert Einstein'] = 50
In [10]:
print(grades)
{'John Smith': 75, 'Alice Brown': 93, 'Walter White': 95, 'Albert Einstein': 50}

Getting the list of keys in the dictionary:

In [11]:
list(grades.keys())
Out[11]:
['John Smith', 'Alice Brown', 'Walter White', 'Albert Einstein']

Getting the list of values of a dictionary:

In [12]:
list(grades.values())
Out[12]:
[75, 93, 95, 50]

Converting dictionary into a nested list:

In [13]:
list(grades.items())
Out[13]:
[('John Smith', 75),
 ('Alice Brown', 93),
 ('Walter White', 95),
 ('Albert Einstein', 50)]

Use dict() to convert a list of lists into a dictionary:

In [16]:
mylist = [['first_n', 'Walter'], ['last_n', 'White'], ['age', 51]]
mydict = dict(mylist)
print(mydict)
{'first_n': 'Walter', 'last_n': 'White', 'age': 51}
In [17]:
mydict['first_n']
Out[17]:
'Walter'

Checking if a key is in a dictionary:

In [18]:
grades
Out[18]:
{'Albert Einstein': 50,
 'Alice Brown': 93,
 'John Smith': 75,
 'Walter White': 95}
In [19]:
'Alice Brown' in grades
Out[19]:
True
In [20]:
'Larry Taylor' in grades
Out[20]:
False

Iteration over a dictionary iterates over its keys:

In [21]:
for k in grades:
    print(k)
John Smith
Alice Brown
Walter White
Albert Einstein
In [26]:
for k in grades:
    print('{:20} score: {}'.format(k, grades[k]))
John Smith           score: 75
Alice Brown          score: 93
Walter White         score: 95
Albert Einstein      score: 50

Note: Dictionary keys must be non-mutable objects (strings, numbers).

In [27]:
final_grades = {['Walter', 'White']: 100}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-ed18afb5cef4> in <module>()
----> 1 final_grades = {['Walter', 'White']: 100}

TypeError: unhashable type: 'list'
In [28]:
final_grades = {('Walter', 'White'): 100}
In [29]:
final_grades[('Walter', 'White')]
Out[29]:
100
In [30]:
final_grades = {50011234:'B-', 50112345:'A', 32601234:'A-'}
In [31]:
final_grades[50011234]
Out[31]:
'B-'

Sorting lists

The sorted() function can be used to sort a list:

In [32]:
mylist = ['this', 'that', 'hello', 'bye', 'road', 'ice']
In [33]:
s_mylist = sorted(mylist)
print(s_mylist)
['bye', 'hello', 'ice', 'road', 'that', 'this']
In [34]:
mylist2 = [1, 0, -100, 2.3, -4.7]
s_mylist2 = sorted(mylist2)
print(s_mylist2)
[-100, -4.7, 0, 1, 2.3]

Use the argument reverse to revert the list:

In [35]:
rs_mylist2 = sorted(mylist2, reverse=True)
print(rs_mylist2)
[2.3, 1, 0, -4.7, -100]
In [36]:
mylist3 = ['hello', 'this', 3, 4, 0, 'bye']
sorted(mylist3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-9dbd01e582f6> in <module>()
      1 mylist3 = ['hello', 'this', 3, 4, 0, 'bye']
----> 2 sorted(mylist3)

TypeError: '<' not supported between instances of 'int' and 'str'

In order to sort such lists as above we need to specify a key function that will be evaluated on list elements prior to comparing them:

In [38]:
sorted(mylist3, key=str)
Out[38]:
[0, 3, 4, 'bye', 'hello', 'this']
In [37]:
str(100)
Out[37]:
'100'
In [46]:
scores = [[8, 2, 3], [6, 3, 7], [1, 4, 9], [6, 1, 4]]
In [40]:
sorted(scores)
Out[40]:
[[1, 4, 9], [6, 1, 4], [6, 3, 7], [8, 2, 3]]
In [47]:
def total_score(s):
    tot = s[0]*0.25 + s[1]*0.25 + s[2]*0.50
    return tot
In [49]:
sorted(scores, key=total_score)
Out[49]:
[[6, 1, 4], [8, 2, 3], [6, 3, 7], [1, 4, 9]]

Counting with dictionaries

The numpy function np.random.randint(low, high, size) generates an array of the given size of random integers from the range low to high:

In [8]:
import numpy as np
In [9]:
numbers = np.random.randint(1, 10, 1000)
In [10]:
numbers
Out[10]:
array([2, 3, 2, 4, 1, 7, 9, 5, 5, 1, 7, 1, 3, 5, 1, 1, 6, 4, 9, 2, 9, 1, 1,
       2, 1, 1, 3, 1, 8, 6, 3, 5, 7, 4, 2, 7, 2, 5, 4, 6, 2, 9, 4, 3, 7, 7,
       4, 5, 6, 6, 3, 4, 1, 9, 1, 2, 1, 7, 4, 9, 4, 7, 3, 1, 6, 3, 8, 7, 4,
       9, 8, 7, 2, 4, 6, 7, 8, 5, 6, 7, 1, 6, 2, 9, 7, 1, 8, 7, 4, 9, 4, 2,
       4, 8, 3, 5, 4, 3, 4, 8, 4, 6, 3, 5, 1, 9, 9, 8, 1, 4, 3, 3, 5, 8, 6,
       8, 9, 4, 7, 9, 4, 8, 1, 2, 5, 4, 4, 4, 7, 5, 4, 6, 2, 2, 7, 6, 5, 3,
       6, 6, 9, 5, 1, 1, 3, 4, 9, 4, 7, 5, 9, 1, 7, 5, 4, 1, 3, 3, 3, 8, 7,
       7, 1, 3, 9, 9, 4, 6, 3, 2, 3, 3, 1, 1, 6, 4, 2, 6, 5, 6, 3, 4, 1, 5,
       3, 7, 5, 7, 6, 5, 9, 9, 2, 3, 2, 5, 2, 7, 2, 7, 3, 5, 2, 4, 1, 5, 8,
       1, 7, 5, 1, 1, 9, 1, 3, 4, 3, 1, 1, 5, 1, 3, 8, 7, 7, 5, 7, 3, 8, 4,
       5, 1, 1, 1, 3, 7, 7, 6, 2, 2, 9, 4, 5, 2, 7, 5, 2, 1, 9, 3, 2, 5, 9,
       4, 5, 7, 8, 9, 4, 5, 9, 8, 6, 6, 2, 1, 4, 2, 2, 9, 5, 2, 1, 6, 9, 9,
       7, 8, 4, 2, 3, 4, 1, 2, 4, 2, 3, 7, 7, 4, 7, 6, 5, 9, 3, 6, 3, 9, 6,
       1, 6, 6, 8, 3, 7, 2,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 3, 1, 5, 7, 4, 5, 4, 9, 4, 6,
       5, 3, 9, 1, 3, 2, 2, 5, 2, 9, 1])
In [11]:
number_counts = {}
for n in numbers:
    if n not in number_counts:
        number_counts[n] = 1
    else:
        number_counts[n] += 1
In [12]:
print(number_counts)
{2: 88, 3: 108, 4: 144, 1: 135, 7: 114, 9: 97, 5: 122, 6: 106, 8: 86}

Bar diagrams

In [13]:
import matplotlib.pyplot as plt
In [33]:
import matplotlib.cm as cm

pop = [1409, 1339, 324, 263]
countries = ['China', 'India', 'USA', 'Indonesia']

x = plt.bar(range(1, len(pop)+1), pop, width= .4,tick_label= countries, color=cm.autumn(.7))
x[1].set_color('r')
plt.xticks(fontsize=15, rotation='vertical')
plt.show()

semilogy semilogx and loglog plots

In [40]:
plt.figure(figsize=(20,5))
x = np.linspace(1, 5, 200)

plt.subplot(141)
plt.title('$y=x^3$', fontsize=20)
plt.plot(x, x**3)

plt.subplot(142)
plt.title('$y=2^x$', fontsize=20)
plt.plot(x, 2**x)

plt.subplot(143)
plt.title('$y=\log(x)$', fontsize=20)
plt.plot(x, np.log(x))


plt.subplot(144)
plt.title('$y=x^{0.5}$', fontsize=20)
plt.plot(x, x**0.5)



plt.show()

semilogy

plt.semilogy(x, y) creates a plot with coordinates (x, log(y)). In this way plots of functions of the form $y=a\cdot b^x$ are becoming straight lines:

In [41]:
plt.figure(figsize=(20,5))
x = np.linspace(1, 5, 200)

plt.subplot(141)
plt.title('$y=x^3$', fontsize=20)
plt.semilogy(x, x**3)

plt.subplot(142)
plt.title('$y=2^x$', fontsize=20)
plt.semilogy(x, 2**x)

plt.subplot(143)
plt.title('$y=\log(x)$', fontsize=20)
plt.semilogy(x, np.log(x))


plt.subplot(144)
plt.title('$y=x^{0.5}$', fontsize=20)
plt.semilogy(x, x**0.5)



plt.show()

semilogx

plt.semilogx(x, y) creates a plot with coordinates (log(x), y). In this way plots of functions of the form $y=a\cdot log(x)$ are becoming straight lines:

In [42]:
plt.figure(figsize=(20,5))
x = np.linspace(1, 5, 200)

plt.subplot(141)
plt.title('$y=x^3$', fontsize=20)
plt.semilogx(x, x**3)

plt.subplot(142)
plt.title('$y=2^x$', fontsize=20)
plt.semilogx(x, 2**x)

plt.subplot(143)
plt.title('$y=\log(x)$', fontsize=20)
plt.semilogx(x, np.log(x))


plt.subplot(144)
plt.title('$y=x^{0.5}$', fontsize=20)
plt.semilogx(x, x**0.5)



plt.show()

loglog

plt.loglog(x, y) creates a plot with coordinates (log(x), log(y)). In this way plots of functions of the form $y=a\cdot x^b$ are becoming straight lines:

In [43]:
plt.figure(figsize=(20,5))
x = np.linspace(1, 5, 200)

plt.subplot(141)
plt.title('$y=x^3$', fontsize=20)
plt.loglog(x, x**3)

plt.subplot(142)
plt.title('$y=2^x$', fontsize=20)
plt.loglog(x, 2**x)

plt.subplot(143)
plt.title('$y=\log(x)$', fontsize=20)
plt.loglog(x, np.log(x))


plt.subplot(144)
plt.title('$y=x^{0.5}$', fontsize=20)
plt.loglog(x, x**0.5)



plt.show()
In [47]:
plt.figure(figsize=(5,5))
x = np.linspace(1, 5, 200)

plt.loglog(x, x**3, label='$y=x^3$')
plt.loglog(x, x**0.5, label='$y=x^{0.5}$')
plt.loglog(x, x**(-0.5), label='$y=x^{-0.5}$')
plt.legend()
plt.show()