https://media.readthedocs.org/pdf/python-practice-book/latest/python-practice-book.
pdf
Dictionary
d = dict() # or d = {}
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
Dict = dict([(1, 'Geeks'), (2, 'For')])
# Creating a Nested Dictionary
Dict = {1: 'Geeks', 2: 'For', 3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
# Updating existing Key's Value
Dict[2] = 'Welcome'
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print(Dict['name'])
# accessing a element using get()
print(Dict.get(3))
# Deleting a Key value
del Dict[1]
# Nested Dictionary
del Dict['A'][2]
# Deleting a Key
Dict.pop(5)
# Deleting entire Dictionary
Dict.clear()
# using str() to display dic as string
print (str(dic))
# using str() to display dic as list
print (dic.items())
dict1 = [ 1, 3, 5, 6 ]
# using len() to display dic size
print (len(dic1))
# using type() to display data type
print (type(dic1))
# using copy() to make shallow copy of dictionary
dic3 = {}
dic3 = dic1.copy()
# printing new dictionary
print (dic3.items())
# clearing the dictionary
dic1.clear()
# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345
{'xyz': 123, 'abc': 345}
# print only the keys or value:
print d.keys() or d.values()
dic1 = { 'Name' : 'Nandini', 'Age' : 19 }
dic2 = { 'ID' : 2541997 }
# using update to add dic2 values in dic 1
dic1.update(dic2)
# printing updated dictionary values
print (str(dic1))
{'Age': 19, 'Name': 'Nandini', 'ID': 2541997}
# Initializing sequence
sequ = ('Name', 'Age', 'ID')
# using fromkeys() to transform sequence into dictionary
dict = dict.fromkeys(sequ,5)
{'Age': 5, 'Name': 5, 'ID': 5}
# using has_key() to check if dic1 has a key
if dict.has_key('Name'):
print ("Name is a key")
else : print ("Name is not a key")
#combining two dictionaries
D1={}
D2={}
D1.update(D2)
# using setdefault() to print a key value
print (dict.setdefault('ID', "No ID"))
{'Name': 'Nandini', 'Age': 19, 'ID': 'No ID'}
# for ascending and descending order
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0)) note: 0 is for key order
sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True) note: 1 is for value order
# for mapping two lists into a dictionaries:
keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
#to find maximum and minimum value
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k])) NOTE: KEY DEFINE S THE CRITERIA OF FINDING MAX AND MIN
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) FOR EXAMPLE IN THIS CASE OUR CRITERIS IS THAT FINDING MAX AND MIN THROUGH
print('Maximum Value: ',my_dict[key_max]) DIC:KEYS
print('Minimum Value: ',my_dict[key_min])
OR
A=list(my_dic.values())
B=list(my_dict.keys())
Print b[A.index(max(A))]
https://www.mfitzp.com/article/python-dictionaries/
:List:
List = []
# Addition of Elements
List.append(1)
List.append(2)
List.append(3)
List after Addition of Three elements:
[1, 2, 4]
# Adding elements to the List
# using Iterator
for i in range(1, 4):
List.append(i)
List after Addition of elements from 1-3:
[1, 2, 4, 1, 2, 3]
# Adding Tuples to the List
List.append((5, 6))
List after Addition of a Tuple:
[1, 2, 4, 1, 2, 3, (5, 6)]
# Addition of List to a List
List2 = ['For', 'Geeks']
List.append(List2)
List after Addition of a List:
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]
# Addition of Element at specific position
List.insert(3, 12)NOTE: HERE 3 IS INDEX
List after performing Insert Operation:
[1, 2, 4, 12, 1, 2, 3, (5, 6), ['Geeks', 'For', 'Geeks']]
# Addition of multiple elements at the end
List.extend([8, 'Geeks', 'Always'])
List after performing Extend Operation:
[1, 2, 4, 12, 1, 2, 3, (5, 6), ['Geeks', 'For', 'Geeks'], 8, 'Geeks', 'Always']
# accessing a element from the list using index
print(List[0])
print(List[2])
# accessing a element from the nested list
print(List[0][1]) NOTE: IT WILL PRINT WITHOUT SQUARE BRACKETS
print(List[1][0:]) NOTE: IT WILL PRINT WITH SQUARE BRACKETS
# accessing a element using negative index
print(List[-1])
#changing elements of list
List=[1, 2,…..]
List[0:2]=[3, 4] NOTE: HERE 2 IS NOT INCLUDE THESE ARE THE INDEX.
Now output is
List=[3, 4,…}
#adding element to list
List=[1, 2, 3, 4]
Print(list + [5, 21 ])
List=[1, 2, 3, 4, 5, 21]
# Removing elements from List
List.remove(5) note: 5 is not the index. It is the element.
# Removing elements from List using iterator method
for i in range(1, 5): note:(1, 5) are not index
List.remove(i)
# removing item from list
Del list[index] NOTE: ITEM AT GIVEN INDEX WILL BE DELETED
# Removing last element
List.pop()
# Removing element with index
List.pop(2) note:2 is index
# Creating a List
List = ['G','E','E','K','S','F', 'O','R','G','E','E','K','S']
# using Slice operation
Sliced_List = List[3:8] NOTE: 3 AND 8 IS INDEX
['K', 'S', 'F', 'O', 'R']
# Print elements from beginning to a pre-defined point using Slice
Sliced_List = List[:-6]
['G', 'E', 'E', 'K', 'S', 'F', 'O']
Sliced_List = List[5:]
['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
# Printing elements from beginning till end
Sliced_List = List[:]
# Printing elements in reverse
Sliced_List = List[::-1]
# Will print the index of '4' in list1
print(list1.index(4))
# Will print the index of 'cat' in list2
print(list2.index('cat'))
# Random list having sublist and tuple also
list1 = [1, 2, 3, [9, 8, 7], ('cat', 'bat')]
# Will print the index of sublist [9, 8, 7]
print(list1.index([9, 8, 7]))
# adding items of list
list=[1, 2, 3, 4, 5]
print(list[1] + list[2])
output is (BC)
#TIPS
x=[1, 2, 3, 4] x=[1 , 2, 3, 4]
y=x y=list(x)
y[1]=4 INSTEAD THIS y=[:]
then, y=[1, 4, 3, 4] y[1]=4
and x=[1, 4, 3, 4] x=[1, 2, 3, 4]
numpy.core.defchararray.index(arr, substring, start=0, end=None): Finds the lowest index of the sub-
string in the specified range But if substring is not found, it raises ValueError.
import numpy as np
arr = ['this is geeks for geek']
print ("arr : ", arr)
print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks'))
arr : ['this is geeks for geek']
index of 'geeks' : [8]
import numpy as np
arr = ['this is geeks for geek']
print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks', start = 2))
print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks', start = 10))
print ("\nindex of 'geek' : ", np.char.index(arr, 'geek', start = 10))
index of 'geeks' : [8]
ValueError: substring not found
index of 'geek' : [18]
list comprehension:
1=[expression for variable in range]
List=[] a/c to comprehension square=[i**2 for x in
For x in range(1, 101): print(square)
Square.append(x**2)
Print(square)
2=[expression for variable in range if <cond>]
List=[movies name] a/c to comprehension movies=[tittle For tittle in list If tittle.startswith(“G”)]
List2=[]
For tittle in list:
If tittle.startswith(“G”)
List2.append(tittle)
3=[expression for variable in range if <cond1> and <cond2>]
List=[(movie, year),…] a/c to comprehension movies=[tittle for key, value in list if value > 200 and
For key, value in list: tittle.startswith(“G”)]
If value>2000
Print(tittle)
4=[expression for variable-1 in range-1 and variable-2 in range-2]
Cartesion product:
A=[1, 2, 3, 4, 5]
B=[1, 2, 3, 4, 5]
List=[(a, b) for a in A for b in B]
Print(list)
print(" LIST COMPREHENSION")
lism=[1, 2, 3, 4, 5]
print("original list",lism)
print(" method # 01")
a=[]
for x in lism:
a.append(x*x)
print(a)
print(" now method # 02")
b=[x*x for x in lism]
print(b)
print(" then method # 03")
c=list(map(lambda x: x*x, lism))
print(c)
print(" method # 04")
d=list(map(square, lism))
print(d)
a=input("enter temperature ")
no=a[:-1]
if a[-1]=="F":
c = int((0.5555) * (no- 32))
print(c,"C")
elif a[-1]=="C":
c=int((1.8)*(1/no -32))
print(c,"F")
else:
print("incorrect input")