Dictionary

In [1]:
#A dictionary can be invoked using the below.
names = {}
In [2]:
type(names)
Out[2]:
dict
In [3]:
#Adding a key value pair to a dictionary.

names['alex'] = 20
In [4]:
names
Out[4]:
{'alex': 20}
In [5]:
names['sam'] = 33
names['john'] = 49
names['albert'] = 10
names['rex'] = 19
In [6]:
names
Out[6]:
{'alex': 20, 'sam': 33, 'john': 49, 'albert': 10, 'rex': 19}
In [7]:
len(names) #Returns the total number of key-value pairs in a dictionary.
Out[7]:
5
In [8]:
#To get Value of a key in a dictionary
names['alex']
Out[8]:
20

Iteration through Dictionary

In [9]:
for name in names:
  print(name)
alex
sam
john
albert
rex
In [10]:
for name in names:
  print(name, names[name])
alex 20
sam 33
john 49
albert 10
rex 19

Dictionary Membership checking

In [11]:
'alex' in names
Out[11]:
True
In [12]:
30 in names #Will check the key only
Out[12]:
False

Deleting dictionary items

In [13]:
del names['alex']
In [14]:
names
Out[14]:
{'sam': 33, 'john': 49, 'albert': 10, 'rex': 19}
In [15]:
#To check if a key is present in a dictionary.

search = input("Enter your name: ")
if search in names:
  print("{} is present".format(search))
else:
  print("{} is not present".format(search))
Enter your name: john
john is present
In [16]:
names.get('sam') #To get the value of a key
Out[16]:
33
In [17]:
names.get('syam', 404) #To print a value if the key doesn't exist in dict
Out[17]:
404
In [18]:
msg = "An operating system consists of various fundamental programs which are needed by your computer so that it can communicate and receive instructions from users; read and write data to hard disks, tapes, and printers; control the use of memory; and run other software. The most important part of an operating system is the kernel. In a GNU Linux system, Linux is the kernel component. The rest of the system consists of other programs, many of which were written by or for the GNU Project. Because the Linux kernel alone does not form a working operating system, we prefer to use the term GNU Linux to refer to systems that many people casually refer to as Linux. "
In [19]:
words = msg.replace(';', '').replace(',', '').replace('.', '').lower().split() #Shown in previous day class to split the string into a list
In [20]:
words
Out[20]:
['an',
 'operating',
 'system',
 'consists',
 'of',
 'various',
 'fundamental',
 'programs',
 'which',
 'are',
 'needed',
 'by',
 'your',
 'computer',
 'so',
 'that',
 'it',
 'can',
 'communicate',
 'and',
 'receive',
 'instructions',
 'from',
 'users',
 'read',
 'and',
 'write',
 'data',
 'to',
 'hard',
 'disks',
 'tapes',
 'and',
 'printers',
 'control',
 'the',
 'use',
 'of',
 'memory',
 'and',
 'run',
 'other',
 'software',
 'the',
 'most',
 'important',
 'part',
 'of',
 'an',
 'operating',
 'system',
 'is',
 'the',
 'kernel',
 'in',
 'a',
 'gnu',
 'linux',
 'system',
 'linux',
 'is',
 'the',
 'kernel',
 'component',
 'the',
 'rest',
 'of',
 'the',
 'system',
 'consists',
 'of',
 'other',
 'programs',
 'many',
 'of',
 'which',
 'were',
 'written',
 'by',
 'or',
 'for',
 'the',
 'gnu',
 'project',
 'because',
 'the',
 'linux',
 'kernel',
 'alone',
 'does',
 'not',
 'form',
 'a',
 'working',
 'operating',
 'system',
 'we',
 'prefer',
 'to',
 'use',
 'the',
 'term',
 'gnu',
 'linux',
 'to',
 'refer',
 'to',
 'systems',
 'that',
 'many',
 'people',
 'casually',
 'refer',
 'to',
 'as',
 'linux']
In [21]:
#To find the number of occurances of a word in a list using dictionary.

words_counter = {}
for word in words:
  if word in words_counter:
    words_counter[word] = words_counter[word] + 1
  else:
    words_counter[word] = 1

words_counter
Out[21]:
{'an': 2,
 'operating': 3,
 'system': 5,
 'consists': 2,
 'of': 6,
 'various': 1,
 'fundamental': 1,
 'programs': 2,
 'which': 2,
 'are': 1,
 'needed': 1,
 'by': 2,
 'your': 1,
 'computer': 1,
 'so': 1,
 'that': 2,
 'it': 1,
 'can': 1,
 'communicate': 1,
 'and': 4,
 'receive': 1,
 'instructions': 1,
 'from': 1,
 'users': 1,
 'read': 1,
 'write': 1,
 'data': 1,
 'to': 5,
 'hard': 1,
 'disks': 1,
 'tapes': 1,
 'printers': 1,
 'control': 1,
 'the': 9,
 'use': 2,
 'memory': 1,
 'run': 1,
 'other': 2,
 'software': 1,
 'most': 1,
 'important': 1,
 'part': 1,
 'is': 2,
 'kernel': 3,
 'in': 1,
 'a': 2,
 'gnu': 3,
 'linux': 5,
 'component': 1,
 'rest': 1,
 'many': 2,
 'were': 1,
 'written': 1,
 'or': 1,
 'for': 1,
 'project': 1,
 'because': 1,
 'alone': 1,
 'does': 1,
 'not': 1,
 'form': 1,
 'working': 1,
 'we': 1,
 'prefer': 1,
 'term': 1,
 'refer': 2,
 'systems': 1,
 'people': 1,
 'casually': 1,
 'as': 1}
In [22]:
#To view words with more than 5 occurances.

for word in words_counter:
  if words_counter[word] > 5:
    print(word, words_counter[word])
of 6
the 9
In [23]:
#To check the file size of all conf files in a folder and save them to a dictionary.

import os
file_counter = {}
for file in os.listdir('/etc'):
  abs_path = os.path.join('/etc/', file)
  if abs_path.endswith('.conf'):
    size = os.path.getsize(abs_path)
    file_counter[abs_path] = size
In [24]:
file_counter
Out[24]:
{'/etc/nsswitch.conf': 497,
 '/etc/mke2fs.conf': 812,
 '/etc/sysctl.conf': 2683,
 '/etc/deluser.conf': 604,
 '/etc/host.conf': 92,
 '/etc/pam.conf': 552,
 '/etc/libaudit.conf': 191,
 '/etc/gai.conf': 2584,
 '/etc/resolv.conf': 141,
 '/etc/adduser.conf': 3028,
 '/etc/ld.so.conf': 34,
 '/etc/debconf.conf': 2969,
 '/etc/ucf.conf': 1260,
 '/etc/ca-certificates.conf': 5898}
In [28]:
#To add multiple values to a dictionary in a go.
d = {'syam':10 , 'rex': 15 , 'jake': 20 , 'alex': 10 , 'sam': 50}
d
Out[28]:
{'syam': 10, 'rex': 15, 'jake': 20, 'alex': 10, 'sam': 50}
In [31]:
d.keys() #To view all keys
Out[31]:
dict_keys(['syam', 'rex', 'jake', 'alex', 'sam'])
In [33]:
list(d) #To view all keys in a list
Out[33]:
['syam', 'rex', 'jake', 'alex', 'sam']
In [34]:
d.values() #To view all values in a dict. 
Out[34]:
dict_values([10, 15, 20, 10, 50])

Tuples

In [35]:
#Tuples are immutable version of a list.
In [36]:
t = ('test' ,'hi', 12 , 'how' , 3456 , 'you')
In [37]:
t[0]
Out[37]:
'test'
In [38]:
for i in t:
  print(i)
test
hi
12
how
3456
you
In [39]:
del t[0] #Tuples doesnt support deletion
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-c3f2aebc449c> in <module>
----> 1 del t[0] #Tuples doesnt support deletion

TypeError: 'tuple' object doesn't support item deletion
In [40]:
t.count('test')
Out[40]:
1
In [41]:
t.index('test')
Out[41]:
0
In [42]:
t.index('you')
Out[42]:
5
In [43]:
t = ('syam', 'fuji',[1,2,3])
In [44]:
len(t[2])
Out[44]:
3
In [45]:
t[2].append(4)
In [46]:
t
Out[46]:
('syam', 'fuji', [1, 2, 3, 4])
In [47]:
del t[2][0]
In [48]:
t
Out[48]:
('syam', 'fuji', [2, 3, 4])
In [50]:
d.items() #The dictionary items will be shown as a list of tuples.
Out[50]:
dict_items([('syam', 10), ('rex', 15), ('jake', 20), ('alex', 10), ('sam', 50)])
In [51]:
for i in d.items():
  name = i[0]
  rank = i[1]
  if rank >= 15:
    print("{} has a rank of {}".format(name,rank))
rex has a rank of 15
jake has a rank of 20
sam has a rank of 50

Unpacking

In [52]:
l = ['syam', 15 , 'syam@gmail.com']
In [53]:
#We can assign the values to a variable like this.

name = l[0]
rank = l[1]
email = l[2]
In [54]:
#Or by this way
name, rank, email = l
In [55]:
for i in d.items():
  name,rank = i
  if rank >= 15:
    print("{} has a rank of {}".format(name,rank))
rex has a rank of 15
jake has a rank of 20
sam has a rank of 50
In [56]:
#It can be further shortened.

for name,rank in d.items():
  if rank >= 15:
    print("{} has a rank of {}".format(name,rank))
rex has a rank of 15
jake has a rank of 20
sam has a rank of 50

Nested Lists

In [57]:
employee = [['alex', 35000] , ['sam' , 40000] , ['jess', 10000] , ['mark' , 23000]]
In [58]:
employee
Out[58]:
[['alex', 35000], ['sam', 40000], ['jess', 10000], ['mark', 23000]]
In [59]:
for name,mark in employee:
  if mark > 25000:
    print(name)
alex
sam

Reading files from Python

In [64]:
file = 'environment.yml'
fh = open(file)
In [65]:
for line in fh:
  print(line)
channels:

  - conda-forge

  - defaults

dependencies:

  - python=3.6

  - cython

  - ipython

  - ipyparallel

  - ipywidgets

  - numpy

  - matplotlib

  - mpi4py

  - networkx

  - pandas

  - scikit-image

  - scikit-learn

  - sympy

In [ ]: