dict,function basics, ways to define a function
dict - Dictionary
#dict is a class
#dict is a type
#dict is iterable
#dict is not a sequence like set
#dict is mutable
#dict doesn't guarantee order
#dict have key, value pairs (key / object)
#keys cannot be duplicate in dict,it must be unique.
#No concept of indexing, slicing.
#unsupported operators - concatenation, inequality (< , > , <=, >=) and repetition operator
BUT equality operator is supported
Ways to create dict object
i) d = {}
ii) d = dict()
Elements can be stored in key and value fashion where first element forms the key and the second becomes value.
Example d = {'a': 'apple', 'b':'ball', 'c': 'cat}
There is slight difference if we use the conversion method dict() to create a dictionary. In that case all the keys are assumed as string and should be updated like keyword argument as dict is a function.
Example - d = dict(a = 'apple', b = 'ball', c = 'cat')
Ways to access elements:
Using loop
for e in d:
print(e)
this would print keys list
a
b
c
if we want to access particular values this works with below syntax
<dictionaryname> followed by [ key ].
Example
d1 = {'Hari': 43848988, 'Sapkota': 24091999}
>>> for e in d1:
... print(e,d1[e])
...
Hari 43848988
Sapkota 24091999
we can unpack key and values in dictionary as tuple is returned.
for key,object in d1:
print(k,o)
>>> for k,o in d.items():
... print(k,o)
...
a apple
b ball
>>>
Modify Objects in dictionary
>>> alphabets = dict(a='apple',b='ball',c='cat')
>>> alphabets
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
if we want to add new element we can do it with below syntax
alphabets['d'] = 'dog'
also we can update existing with
alphabets['b'] = 'banana
>>> alphabets['d'] = 'dog'
>>> alphabets
{'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
>>> alphabets['c'] = 'banana'
>>> alphabets
{'a': 'apple', 'b': 'ball', 'c': 'banana', 'd': 'dog'}
>>>'
Delete keys
del alphabets['a']
Or, using pop and pop items methods
alphabets.pop('key')
alphabets.popitem() - WITHOUT Arguments
dict comprehension
d1 = {expression1: expression2 for e in iterable }
expression 1 : key
expression 2: value
Functions
Block of code
#function definition
def f1():
print("Hello")
a = 10
b = 20
c = a+b
print(c)
f1() # function call
Note : if there are multiple declaration of function then no error in python. It will execute function based on precedence as code is interpreted line by line.
#ways to define a function
#1 Take something return something
#2 Take something return nothing
#3 Take nothing return something
#4 Take nothing return nothing
Same concept as C/C++.
def f1(): #function definition
a,b=10,20
print( f2(a,b))
def f2(x,y):
c = x + y
return c
f1() #function call
Comments
Post a Comment