In [237]:
Agenda = '''
Quick Python Introduction, 
Anaconda Python3,
Data Types
int, float , str, bool , complex 
Data Structure
Mutable : List, Dictionary, ( Set )
Immutable : Tuple, String, ( Number ) 
Control Structure
if elif else
while 
for 
User Define Functions
function with parameter
global Variable
fibbonacci Sequence 
factorial of number
Variable Argument *arg, **kwarg
Multiplier
Python Built in Functions
    lambda
    filter
    map
    max, min, sum
    set
    sorted
    reversed
    zip
List Comprehension, 
Dictionary Comprehension
Dictionary Case Study
Summary
'''
In [3]:
type(True)
Out[3]:
bool
In [4]:
True + True + True - False
Out[4]:
3
In [24]:
Str1 = 'surendra panpaliya'
In [6]:
Str1[::-1]
Out[6]:
'ARDNERUS'
In [9]:
Str1[0:len(Str1):2]
Out[9]:
'SRNR APLY'
In [11]:
list(range(0,10,2))
Out[11]:
[0, 2, 4, 6, 8]

Data Types:

1) int   #Classes 
2) float  
3) str
4) bool
5) complex

Arithmetic Operation

In [14]:
2**1000
Out[14]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [33]:
#dir('hello')
#type('Hello')
#help(str)
print(Str1.upper())
print(Str1)

co_nu = 5 + 100j

type(co_nu)

num = complex(5,10)
print(num)
print(num.real)
print(num.imag)
print(num.conjugate())
SURENDRA PANPALIYA
surendra panpaliya
(5+10j)
5.0
10.0
(5-10j)

Data Structure

Mutable DS : list, dictionary, set 
Immutable DS : tuple, string, numbers

What is List in Python?

List is mutable sequence of any objects like int, float,string, complex, list, tuple , many more.
In [34]:
List1 = []
type(List1)
Out[34]:
list
In [35]:
List2 = list()
List2
Out[35]:
[]

List as a Stack

In [37]:
Books = []
Books.append('Python')
Books.append('Jython')
Books.append('Java')
Books.append('Cython')
Books.append('J2ee')
Books.append('Spring')
Books.append('Ruby')
print(Books)
Books.pop()
print(Books)
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring']

List as a Queue

In [38]:
Books = []
Books.append('Python')
Books.append('Jython')
Books.append('Java')
Books.append('Cython')
Books.append('J2ee')
Books.append('Spring')
Books.append('Ruby')
print(Books)
Books.pop(0)
print(Books)
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']
['Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']

List as a Link List

In [40]:
Books = []
Books.append('Python')
Books.append('Jython')
Books.append('Java')
Books.append('Cython')
Books.append('J2ee')
Books.append('Spring')
Books.append('Ruby')
print(Books)
Books.insert(2,'Ruby on Rails')
print(Books)
Books.remove('Jython')
print(Books)
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']
['Python', 'Jython', 'Ruby on Rails', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']
['Python', 'Ruby on Rails', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']

Update List

In [42]:
Books = []
Books.append('Python')
Books.append('Jython')
Books.append('Java')
Books.append('Cython')
Books.append('J2ee')
Books.append('Spring')
Books.append('Ruby')
print(Books[2])
Books[2]='Perl'
print(Books)
Java
['Python', 'Jython', 'Perl', 'Cython', 'J2ee', 'Spring', 'Ruby']

Extend List by new List

In [43]:
Books = []
Books.append('Python')
Books.append('Jython')
Books.append('Java')
Books.append('Cython')
Books.append('J2ee')
Books.append('Spring')
Books.append('Ruby')
print(Books)
Book1 = ['Mongodb','Django','DataScience']
Books.extend(Book1)
print(Books)
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby', 'Mongodb', 'Django', 'DataScience']
In [52]:
# Sort List

Books = []
Books.append('Python')
Books.append('Jython')
Books.append('Java')
Books.append('Cython')
Books.append('J2ee')
Books.append('Spring')
Books.append('Ruby')
print(Books)
Book1 = ['Mongodb','Django','DataScience']
Books.extend(Book1)
print(Books)
Books.sort()
# Index Position of Django 
print(Books.index('Django',1,7))
print(Books)
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby']
['Python', 'Jython', 'Java', 'Cython', 'J2ee', 'Spring', 'Ruby', 'Mongodb', 'Django', 'DataScience']
2
['Cython', 'DataScience', 'Django', 'J2ee', 'Java', 'Jython', 'Mongodb', 'Python', 'Ruby', 'Spring']

Tuple

Tuple is an immutable sequence of any objects like int,float,string, complex, list, tuple , many more.

In [56]:
Book1 = ('Mongodb','Django','DataScience')
type(Book1)
Book1[0] = 'Java'
# Tuples are immutable sequence
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-56-7a3eb969fe0f> in <module>
      1 Book1 = ('Mongodb','Django','DataScience')
      2 type(Book1)
----> 3 Book1[0] = 'Java'
      4 # Tuples are immutable sequence

TypeError: 'tuple' object does not support item assignment
In [57]:
dir(Book1)
Out[57]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'count',
 'index']
In [65]:
Tup1 = 'hello', 23, 55, 5.0
print(Tup1)
type(Tup1)
Tup2 = (5)
print(type(Tup2))
Tup3 = (5,)
print(type(Tup3))
print(Tup3)
('hello', 23, 55, 5.0)
<class 'int'>
<class 'tuple'>
(5,)

Swapping in Python

In [66]:
first = 45
second = 56.9
temp = first
first = second
second = temp
print(first)
print(second)
56.9
45
In [67]:
first, second = 45, 56.9  # parallel Assignment 
first, second = second, first
print(first, second)
56.9 45
In [68]:
first, second, third, fourth = 45, 56.9, 'hello',True
# parallel Assignment 
first, second, third, fourth = fourth, third, second,first
print(first, second, third, fourth)
True hello 56.9 45
In [70]:
import time
TL = time.localtime()
print(TL)
type(TL)
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=6, tm_hour=11, tm_min=35, tm_sec=39, tm_wday=0, tm_yday=6, tm_isdst=0)
Out[70]:
time.struct_time
In [75]:
year, mon, mday, hour, minute, sec, wday, \
yday, isdst = time.localtime()

print(year, mon, mday, hour, minute, sec, wday, \
yday, isdst)
In [78]:
Tuple_Time = (year, mon, mday, hour, minute, sec, wday, \
yday, isdst)
In [84]:
Tuple_Time[0:3]
Out[84]:
(2020, 1, 6)
In [85]:
print(mday, mon, year)
6 1 2020

Dictionary

Dictionary is an unorder collection of unique, immutable, key and mutable or immutable values.
In [86]:
Routers = {}
type(Routers)
Out[86]:
dict
In [87]:
Routers = {}
Routers['cisco26'] = 'cisco2600'
Routers['cisco72'] = 'cisco7200'
Routers['cisco32'] = 'cisco3200'
Routers['ip'] = '10.10.10.1'
Routers['subnet'] = '255.255.255.0'
print(Routers)
{'cisco26': 'cisco2600', 'cisco72': 'cisco7200', 'cisco32': 'cisco3200', 'ip': '10.10.10.1', 'subnet': '255.255.255.0'}
In [88]:
Routers.keys()
Out[88]:
dict_keys(['cisco26', 'cisco72', 'cisco32', 'ip', 'subnet'])
In [89]:
Routers.values()
Out[89]:
dict_values(['cisco2600', 'cisco7200', 'cisco3200', '10.10.10.1', '255.255.255.0'])
In [91]:
Routers['ip'] = '192.168.2.1'
print(Routers)
{'cisco26': 'cisco2600', 'cisco72': 'cisco7200', 'cisco32': 'cisco3200', 'ip': '192.168.2.1', 'subnet': '255.255.255.0'}
In [92]:
Routers.get('ip')
Out[92]:
'192.168.2.1'
In [93]:
Routers.pop('cisco26')
print(Routers)
{'cisco72': 'cisco7200', 'cisco32': 'cisco3200', 'ip': '192.168.2.1', 'subnet': '255.255.255.0'}
In [94]:
Switch1 = {'cisco82': 'cisco8200', 
           'cisco82': 'cisco8200', 
           'ip': '192.168.2.6', 
           'subnet': '255.255.255.7'}
Routers.update(Switch1)
print(Routers)
{'cisco72': 'cisco7200', 'cisco32': 'cisco3200', 'ip': '192.168.2.6', 'subnet': '255.255.255.7', 'cisco82': 'cisco8200'}
In [95]:
Routers.keys()
Out[95]:
dict_keys(['cisco72', 'cisco32', 'ip', 'subnet', 'cisco82'])
In [96]:
Routers.items()
Out[96]:
dict_items([('cisco72', 'cisco7200'), ('cisco32', 'cisco3200'), ('ip', '192.168.2.6'), ('subnet', '255.255.255.7'), ('cisco82', 'cisco8200')])
In [97]:
for key, value in Routers.items():
    print(key, value)
cisco72 cisco7200
cisco32 cisco3200
ip 192.168.2.6
subnet 255.255.255.7
cisco82 cisco8200

Control Structure

In [98]:
data = 34
 print(data)
  File "<ipython-input-98-9c54c2d18437>", line 2
    print(data)
    ^
IndentationError: unexpected indent
In [99]:
data = 34
print(data)
34
In [102]:
first = int(input("Enter first value:"))
print(first)
print(type(first))
Enter first value:3434
3434
<class 'int'>
In [105]:
%%writefile greatest_three.py

first = int(input("Enter first value:"))
second = int(input("Enter second value:"))
third = int(input("Enter third value:"))
if first > second and first > third:
    print('first is greatest',first)
elif second > third:
    print('second is greatest',second)
else:
    print('third is greatest',third)
Overwriting greatest_three.py
In [106]:
run greatest_three.py
Enter first value:23
Enter second value:534
Enter third value:64
second is greatest 534
In [107]:
%%writefile greatest_three1.py

first = int(input("Enter first value:"))
second = int(input("Enter second value:"))
third = int(input("Enter third value:"))
if first > second and first > third:
    print('first is greatest',first)
elif second > third:
    print('second is greatest',second)
elif first == second:
    print("First is equal to Second")
else:
    print('third is greatest',third)
Writing greatest_three1.py
In [108]:
run greatest_three1.py
Enter first value:34
Enter second value:34
Enter third value:56
First is equal to Second
In [109]:
%%writefile greatest_three_while.py


while True:
    first = int(input("Enter first value:"))
    second = int(input("Enter second value:"))
    third = int(input("Enter third value:"))
    if first > second and first > third:
        print('first is greatest',first)
    elif second > third:
        print('second is greatest',second)
    elif first == second:
        print("First is equal to Second")
    else:
        print('third is greatest',third)
        break
Writing greatest_three_while.py
In [110]:
run greatest_three_while.py
Enter first value:43
Enter second value:64
Enter third value:34
second is greatest 64
Enter first value:43
Enter second value:23
Enter third value:699
third is greatest 699
In [111]:
list(range(0,20,2))
Out[111]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [112]:
list(range(20,0,-2))
Out[112]:
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
In [114]:
Books
for item in Books:
    print(item)
Cython
DataScience
Django
J2ee
Java
Jython
Mongodb
Python
Ruby
Spring
In [116]:
for item in Books:
    print(Books.index(item),item)
0 Cython
1 DataScience
2 Django
3 J2ee
4 Java
5 Jython
6 Mongodb
7 Python
8 Ruby
9 Spring
In [118]:
for item in range(0,len(Books)):
    print(item, Books[item])
0 Cython
1 DataScience
2 Django
3 J2ee
4 Java
5 Jython
6 Mongodb
7 Python
8 Ruby
9 Spring
In [120]:
for index, value in enumerate(Books,1):
    print(index, value)
1 Cython
2 DataScience
3 Django
4 J2ee
5 Java
6 Jython
7 Mongodb
8 Python
9 Ruby
10 Spring
In [123]:
Switch1
Out[123]:
{'cisco82': 'cisco8200', 'ip': '192.168.2.6', 'subnet': '255.255.255.7'}
In [124]:
Routers
Out[124]:
{'cisco72': 'cisco7200',
 'cisco32': 'cisco3200',
 'ip': '192.168.2.6',
 'subnet': '255.255.255.7',
 'cisco82': 'cisco8200'}
In [128]:
for item in Routers:
    print(item,Routers[item])
cisco72 cisco7200
cisco32 cisco3200
ip 192.168.2.6
subnet 255.255.255.7
cisco82 cisco8200

User Define Functions

In [130]:
def function_name(arg1,arg2):
    '''Document of function'''
    print("Welcome to Python Function")
    print("Argument1 %s and Argument2 %s"%(arg1,arg2))
    
    
function_name('Surendra','Panpaliya')
Welcome to Python Function
Argument1 Surendra and Argument2 Panpaliya
In [132]:
%%writefile func_ex.py

def function_name(arg1=None,arg2=None):
    '''Document of function'''
    print("Welcome to Python Function")
    print("Argument1 %s and Argument2 %s"%(arg1,arg2))
    

function_name()
function_name('Surendra','Panpaliya')
Writing func_ex.py
In [133]:
run func_ex.py
Welcome to Python Function
Argument1 None and Argument2 None
Welcome to Python Function
Argument1 Surendra and Argument2 Panpaliya

Assignment1

Create Fibbonanci Sequence using Function

0, 1, 1, 2 , 3, 5, 8, 
In [135]:
def fibbonacci(max_num):
    '''Fibbonacci Sequence up to max_num '''
    first, second = 0, 1
    print(first)
    while second < max_num:
        print(second)
        first, second = second, first + second
        
fibbonacci(50)
0
1
1
2
3
5
8
13
21
34
In [138]:
def fibbonacci(max_num):
    '''Fibbonacci Sequence up to max_num '''
    first, second = 0, 1
    print(first)
    for num in range(max_num):
        print(second)
        first, second = second, first + second
        
fibbonacci(10)
0
1
1
2
3
5
8
13
21
34
55
In [139]:
#Assignment2

def factorial(num):
    '''Factorial of any number'''
    if num <= 0:
        return 1
    else:
        return num * factorial(num -1 )
    
factorial(6)
Out[139]:
720
In [141]:
def factorial1(num):
    '''Factorial of any number'''
    result = 1
    for x in range(1,num+1):
        result = result * x
    return result
    
factorial1(6)
Out[141]:
720
In [142]:
help(factorial)
Help on function factorial in module __main__:

factorial(num)
    Factorial of any number

In [144]:
#dir(factorial)
factorial.__doc__
Out[144]:
'Factorial of any number'
In [146]:
# Local Variable in Python 
def local_func(num):
    '''Local Function'''
    print("Variable without assignment",num)
    num = 200
    print("Variable after Assignment",num)
    

num = 300
local_func(400)
print("Variable after Local function",num)
Variable without assignment 400
Variable after Assignment 200
Variable after Local function 300
In [147]:
# Local Variable in Python 
def global_func():
    '''Global Function'''
    global num
    print("Variable without assignment",num)
    num = 200
    print("Variable after Assignment",num)
    

num = 300
global_func()
print("Variable after global function",num)
Variable without assignment 300
Variable after Assignment 200
Variable after global function 200
In [151]:
def vararg(arg1,arg2=0, *arg, **kwarg):
    '''Variable Argument Function'''
    print("Argument1 %s and Argument2 %s"%(arg1,arg2))
    print("Variable Arguments",arg)
    print(" Default Variable Arguments",kwarg)
    

vararg('first')
print("\n")
vararg('first','second')
print("\n")
vararg('first','second','third',5,6,7,87,'last')
print("\n")
vararg('first','second','third', 56, forth = 4, fifth = 5)
Argument1 first and Argument2 0
Variable Arguments ()
 Default Variable Arguments {}


Argument1 first and Argument2 second
Variable Arguments ()
 Default Variable Arguments {}


Argument1 first and Argument2 second
Variable Arguments ('third', 5, 6, 7, 87, 'last')
 Default Variable Arguments {}


Argument1 first and Argument2 second
Variable Arguments ('third', 56)
 Default Variable Arguments {'forth': 4, 'fifth': 5}
Assignment 3 Create Multiplier function which takes any number of numeric argument and return multiplier of all arguments. def multiplier(*arg): return 2*4*8
In [153]:
def multiplier(*arg):
    '''Multiplier of any number '''
    result = 1
    for i in arg:
        result = result * i
    return result

print(multiplier(2,3,5,8))
print(multiplier(1,2,3,4))
240
24

Built in Functions in Python

lambda
filter
map
max, min, sum
set
sorted
reversed
zip

lambda

Lambda is single line annonymus function.

In [154]:
add = lambda arg1, arg2 : arg1 + arg2

add(34, 56)
Out[154]:
90

filter Function

filter is a function with two arguments
    1) function
    2) sequence

 filter return those values from sequence where function is True.
In [157]:
list(filter(lambda arg1 : arg1 % 2 != 0 
and arg1 % 3 !=0, range(2,25)))
Out[157]:
[5, 7, 11, 13, 17, 19, 23]
In [158]:
fun = lambda arg1 : arg1 % 2 != 0 and arg1 % 3 !=0
In [162]:
print(fun(2))
print(fun(5))
False
True
In [163]:
Salary = [2000, 4000, 5000, 2300, 32000, 8999, 30000]

list(filter(lambda arg1 : arg1 > 2000 
and arg1 < 25000, Salary))
Out[163]:
[4000, 5000, 2300, 8999]

Map

Map is a function which takes two or more arguments. First argument is function and second is one or more sequences, provided number of arguments to function are same as number of sequences.

In [165]:
list(map(lambda arg1 : arg1*3 , Salary))
Out[165]:
[6000, 12000, 15000, 6900, 96000, 26997, 90000]
In [166]:
list(map(lambda arg1 : arg1*3 , Salary))
Out[166]:
[6000, 12000, 15000, 6900, 96000, 26997, 90000]
In [167]:
Salary1 = [2000, 4000, 5000, 2300, 32000, 8999, 30000]
Salary2 = [3000, 5000, 6000, 4300, 52000, 9999, 40000]
list(map(lambda arg1, arg2 : arg1 + arg2, 
         Salary1, Salary2))
Out[167]:
[5000, 9000, 11000, 6600, 84000, 18998, 70000]

min, max and sum Functions

In [169]:
print(min(Salary))
print(max(Salary))
print(sum(Salary))
2000
32000
84299
In [170]:
print(max(Salary1 + Salary2))
52000
In [171]:
print(sum(Salary1 + Salary2))
204598

Set Function

Set is a unorder collection of unique, immutable objects.
In [175]:
Salary1 = [2000, 4000, 5000, 2300, 32000, 5000, 
           2000, 8999, 30000]
Salary2 = [3000, 5000, 6000, 4300, 3000,
           52000, 9999, 40000, 5000]
In [177]:
Set1 = set(Salary1)
print(Set1)
Set2 = set(Salary2)
print(Set2)
{32000, 4000, 8999, 5000, 2000, 30000, 2300}
{52000, 40000, 5000, 4300, 9999, 6000, 3000}
In [179]:
40000 in Set1
Out[179]:
False

Union of Sets

In [188]:
Set3 = Set1.union(Set2)
print(Set3)

Set4 = Set1 | Set2
print(Set4)

print(Set3.issuperset(Set1))
print(Set1.issubset(Set3))
{32000, 4000, 52000, 40000, 8999, 5000, 4300, 9999, 2000, 30000, 6000, 3000, 2300}
{32000, 4000, 52000, 40000, 8999, 5000, 4300, 9999, 2000, 30000, 6000, 3000, 2300}
True
True

Intersection of Set

In [187]:
Set5 = Set1.intersection(Set2)
print(Set5)

Set6 = Set1 & Set2
print(Set6)

print(Set5.issuperset(Set1))
print(Set1.issubset(Set6))
{5000}
{5000}
False
False
In [193]:
sorted(Set1)
Out[193]:
[2000, 2300, 4000, 5000, 8999, 30000, 32000]
In [194]:
sorted(Set1, reverse = True)
Out[194]:
[32000, 30000, 8999, 5000, 4000, 2300, 2000]
In [196]:
list(reversed(Salary1))
Out[196]:
[30000, 8999, 2000, 5000, 32000, 2300, 5000, 4000, 2000]
In [199]:
List1 = list(reversed('SURENDRA'))
print(List1)
['A', 'R', 'D', 'N', 'E', 'R', 'U', 'S']
In [202]:
Str3 = ':'.join(List1)
print(Str3)
A:R:D:N:E:R:U:S
In [203]:
List2 = Str3.split(':')
print(List2)
['A', 'R', 'D', 'N', 'E', 'R', 'U', 'S']
In [209]:
Str4 = ' '.join(List1)
print(Str4)
A R D N E R U S
In [210]:
List3 = Str4.split()
print(List3)
['A', 'R', 'D', 'N', 'E', 'R', 'U', 'S']
In [211]:
Salary1
Out[211]:
[2000, 4000, 5000, 2300, 32000, 5000, 2000, 8999, 30000]
In [212]:
Salary2
Out[212]:
[3000, 5000, 6000, 4300, 3000, 52000, 9999, 40000, 5000]
In [213]:
list(zip(Salary1, Salary2))
Out[213]:
[(2000, 3000),
 (4000, 5000),
 (5000, 6000),
 (2300, 4300),
 (32000, 3000),
 (5000, 52000),
 (2000, 9999),
 (8999, 40000),
 (30000, 5000)]
In [214]:
dict(zip(Salary1, Salary2))
Out[214]:
{2000: 9999,
 4000: 5000,
 5000: 52000,
 2300: 4300,
 32000: 3000,
 8999: 40000,
 30000: 5000}
In [215]:
Que = ['name','age','city','state','country']
Ans = ['Surendra','42','Pune','Maharashtra','India']
In [216]:
for q, a in zip(Que, Ans):
    print("What's your %s, it is %s"%(q,a))
What's your name, it is Surendra
What's your age, it is 42
What's your city, it is Pune
What's your state, it is Maharashtra
What's your country, it is India

List Comprehension

In [219]:
[ num for num in range(2,25) if num % 2 !=0 and 
num % 3 != 0 ]
Out[219]:
[5, 7, 11, 13, 17, 19, 23]
In [220]:
[ (num, num**3) for num in range(2,25) 
 if num % 2 !=0 and num % 3 != 0 ]
Out[220]:
[(5, 125),
 (7, 343),
 (11, 1331),
 (13, 2197),
 (17, 4913),
 (19, 6859),
 (23, 12167)]

Assignment4

Words = ['abc','def','ghi','jkl']

Expected List using List Comprehension

['a','b','c','d'....'l']

In [222]:
Words = ['abc','def','ghi','jkl']
In [224]:
[ ch for word in Words for ch in word ]
Out[224]:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
In [225]:
[ (ch, ord(ch)) for word in Words for ch in word ]
Out[225]:
[('a', 97),
 ('b', 98),
 ('c', 99),
 ('d', 100),
 ('e', 101),
 ('f', 102),
 ('g', 103),
 ('h', 104),
 ('i', 105),
 ('j', 106),
 ('k', 107),
 ('l', 108)]
In [226]:
[ (ch, ord(ch), ch.upper()) for word in Words 
 for ch in word ]
Out[226]:
[('a', 97, 'A'),
 ('b', 98, 'B'),
 ('c', 99, 'C'),
 ('d', 100, 'D'),
 ('e', 101, 'E'),
 ('f', 102, 'F'),
 ('g', 103, 'G'),
 ('h', 104, 'H'),
 ('i', 105, 'I'),
 ('j', 106, 'J'),
 ('k', 107, 'K'),
 ('l', 108, 'L')]
In [228]:
Dict1 = dict(zip(Que,Ans))
print(Dict1)
{'name': 'Surendra', 'age': '42', 'city': 'Pune', 'state': 'Maharashtra', 'country': 'India'}
In [230]:
{ key : value for key, value in Dict1.items() }
Out[230]:
{'name': 'Surendra',
 'age': '42',
 'city': 'Pune',
 'state': 'Maharashtra',
 'country': 'India'}
In [232]:
Dict2 = { value : key for key, value in Dict1.items() }
In [233]:
Dict2
Out[233]:
{'Surendra': 'name',
 '42': 'age',
 'Pune': 'city',
 'Maharashtra': 'state',
 'India': 'country'}
In [236]:
{ key : value for key, value in Dict1.items() 
 if value == '42' }
Out[236]:
{'age': '42'}
In [240]:
# %load BooksApp.py
'''
Dictionary Application will consist of 
Books Dictionay, 
Authors Dictionary and 
Publishers Dictionary. This will include relation of 
Authors with Book ( Many to Many )
Relation of Publisher with Book ( One to One )
'''

# Step 1. Create Publisher Dictionary 

print("*** Publishers Dictionary ****\n")

Publisher1 = { 'pid' : 1, 'pname' : 'Orielly Pub',
              'pcity' : 'Chennai', 
              'pweb' : 'https://www.orielly.org' }

print(Publisher1)

Publisher2 = { 'pid' : 2, 'pname' : 'BPB Pub',
              'pcity' : 'Delhi', 
              'pweb' : 'https://www.bpb.org' }

print(Publisher2)

Publisher3 = { 'pid' : 3, 'pname' : 'TataMcgraw Pub',
              'pcity' : 'Mumbai', 
              'pweb' : 'https://www.tatamcgraw.org' }

print(Publisher3)

Publishers = {}
Publishers['P1'] = Publisher1
Publishers['P2'] = Publisher2
Publishers['P3'] = Publisher3

print("\n")
print("*** Publishers Dictionary ****\n")
print(Publishers)

# Step2 Create Authors Dictionary


print("\n")
print("*** Authors Dictionary ****\n")

Author1 = {'first_name' : 'Surendra', 
           'last_name' : 'Panpaliya',
          'city' : 'Pune',
          'email' : 'surendra@gktcs.com' }

print(Author1)

Author2 = {'first_name' : 'Narendra', 
           'last_name' : 'Panpaliya',
          'city' : 'Pune',
          'email' : 'narendra@gktcs.com' }

print(Author2)

Author3 = {'first_name' : 'Satish', 
           'last_name' : 'Panpaliya',
          'city' : 'Chicago',
          'email' : 'satish@gktcs.com' }

print(Author3)

Authors = { }

Authors['A1'] = Author1

Authors['A2'] = Author2

Authors['A3'] = Author3

print("\n")

print("*** Authors Dictionary ****\n")

print(Authors)

print("*** Books Dictionary ****\n")

print("\n")

Book1 = { 'title' : 'Bytes of Python',
        'publisher' : Publishers['P1'], 
        'authors' : [ Authors['A1'], Authors['A2'] ],
        'pub_date' : '21-09-2019' }


Book2 = { 'title' : 'Django',
        'publisher' : Publishers['P1'], 
        'authors' : [ Authors['A2'], Authors['A3'] ],
        'pub_date' : '20-09-2019' }


Book3 = { 'title' : 'Data Science',
        'publisher' : Publishers['P1'], 
        'authors' : [ Authors['A1'], Authors['A3'] ],
        'pub_date' : '23-09-2019' }


Books = { }

Books['B1'] = Book1

print(Books['B1'])

Books['B2'] = Book2

Books['B3'] = Book3


print("**** Books Library***")

Books
*** Publishers Dictionary ****

{'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}
{'pid': 2, 'pname': 'BPB Pub', 'pcity': 'Delhi', 'pweb': 'https://www.bpb.org'}
{'pid': 3, 'pname': 'TataMcgraw Pub', 'pcity': 'Mumbai', 'pweb': 'https://www.tatamcgraw.org'}


*** Publishers Dictionary ****

{'P1': {'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}, 'P2': {'pid': 2, 'pname': 'BPB Pub', 'pcity': 'Delhi', 'pweb': 'https://www.bpb.org'}, 'P3': {'pid': 3, 'pname': 'TataMcgraw Pub', 'pcity': 'Mumbai', 'pweb': 'https://www.tatamcgraw.org'}}


*** Authors Dictionary ****

{'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}
{'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}
{'first_name': 'Satish', 'last_name': 'Panpaliya', 'city': 'Chicago', 'email': 'satish@gktcs.com'}


*** Authors Dictionary ****

{'A1': {'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}, 'A2': {'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}, 'A3': {'first_name': 'Satish', 'last_name': 'Panpaliya', 'city': 'Chicago', 'email': 'satish@gktcs.com'}}
*** Books Dictionary ****



{'title': 'Bytes of Python', 'publisher': {'pid': 1, 'pname': 'Orielly Pub', 'pcity': 'Chennai', 'pweb': 'https://www.orielly.org'}, 'authors': [{'first_name': 'Surendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'surendra@gktcs.com'}, {'first_name': 'Narendra', 'last_name': 'Panpaliya', 'city': 'Pune', 'email': 'narendra@gktcs.com'}], 'pub_date': '21-09-2019'}
**** Books Library***
Out[240]:
{'B1': {'title': 'Bytes of Python',
  'publisher': {'pid': 1,
   'pname': 'Orielly Pub',
   'pcity': 'Chennai',
   'pweb': 'https://www.orielly.org'},
  'authors': [{'first_name': 'Surendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'surendra@gktcs.com'},
   {'first_name': 'Narendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'narendra@gktcs.com'}],
  'pub_date': '21-09-2019'},
 'B2': {'title': 'Django',
  'publisher': {'pid': 1,
   'pname': 'Orielly Pub',
   'pcity': 'Chennai',
   'pweb': 'https://www.orielly.org'},
  'authors': [{'first_name': 'Narendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'narendra@gktcs.com'},
   {'first_name': 'Satish',
    'last_name': 'Panpaliya',
    'city': 'Chicago',
    'email': 'satish@gktcs.com'}],
  'pub_date': '20-09-2019'},
 'B3': {'title': 'Data Science',
  'publisher': {'pid': 1,
   'pname': 'Orielly Pub',
   'pcity': 'Chennai',
   'pweb': 'https://www.orielly.org'},
  'authors': [{'first_name': 'Surendra',
    'last_name': 'Panpaliya',
    'city': 'Pune',
    'email': 'surendra@gktcs.com'},
   {'first_name': 'Satish',
    'last_name': 'Panpaliya',
    'city': 'Chicago',
    'email': 'satish@gktcs.com'}],
  'pub_date': '23-09-2019'}}
In [244]:
import random
random.randint(1,4)
Out[244]:
4
In [245]:
#Feedback Link 

#https://www.surveymonkey.com/r/CGH9NG8
In [255]:
import yaml

ymldata= '''
   - eggs
   - ham
   - spam
   - French basil salmon terrine
   '''

with open('foo.yaml','w') as f:
    f.write(ymldata)
In [256]:
import yaml

if __name__ == '__main__':
    stream = open("foo.yaml", 'r')
    data = yaml.load(stream, Loader=yaml.FullLoader)
    for item in data:
        print(item)
eggs
ham
spam
French basil salmon terrine
In [257]:
pip install pyyaml
Requirement already satisfied: pyyaml in ./anaconda3/lib/python3.6/site-packages (5.1.2)
Note: you may need to restart the kernel to use updated packages.
In [258]:
%%writefile items.yaml

raincoat: 1
coins: 5
books: 23
spectacles: 2
chairs: 12
pens: 6
Writing items.yaml
In [259]:
%%writefile data.yaml
cities:
  - Bratislava
  - Kosice
  - Trnava
  - Moldava
  - Trencin
---
companies:
  - Eset
  - Slovnaft
  - Duslo Sala
  - Matador Puchov
Writing data.yaml
In [260]:
import yaml

with open('items.yaml') as f:
    
    data = yaml.load(f, Loader=yaml.FullLoader)
    print(data)
{'raincoat': 1, 'coins': 5, 'books': 23, 'spectacles': 2, 'chairs': 12, 'pens': 6}
In [261]:
import yaml

with open('data.yaml') as f:
    
    docs = yaml.load_all(f, Loader=yaml.FullLoader)

    for doc in docs:
        
        for k, v in doc.items():
            print(k, "->", v)
cities -> ['Bratislava', 'Kosice', 'Trnava', 'Moldava', 'Trencin']
companies -> ['Eset', 'Slovnaft', 'Duslo Sala', 'Matador Puchov']
In [262]:
import yaml

users = [{'name': 'John Doe', 'occupation': 'gardener'},
         {'name': 'Lucy Black', 'occupation': 'teacher'}]

print(yaml.dump(users))
- name: John Doe
  occupation: gardener
- name: Lucy Black
  occupation: teacher

In [263]:
import yaml

with open('items.yaml') as f:
    
    data = yaml.load(f, Loader=yaml.FullLoader)
    print(data)

    sorted = yaml.dump(data, sort_keys=True)
    print(sorted)
{'raincoat': 1, 'coins': 5, 'books': 23, 'spectacles': 2, 'chairs': 12, 'pens': 6}
books: 23
chairs: 12
coins: 5
pens: 6
raincoat: 1
spectacles: 2

In [1]:
import yaml
In [ ]: