Python3 Dictionaries DS
Python Data Structures : Dictionaries
Dictionary
Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key : value pair.
Dict Creation :
Eg:
#empty dictionarymy_dict={}#dictionary with integers as keysmy_dict={1:'a',2:'b"}print(my_dict)#dictionary with mixed keysmy_dict={'name':'satish',1:['abc','xy']}print(my_dict)#create empty dictionary using dict( )my_dict=dict()my_dict=dict([(1,'abc'),(2,'xy')]) #create a dict with list of tuplesprint(my_dict)
output: {1:'a',2:'b'}
{'name':'satish',1:['abc','xy']}
{1:'abc',2:'xy'}
Dict Access :
Eg:
my_dict={'name': 'suma','year':2020}print(my_dict['name'])#if key is not present it gives KeyErrorprint(my_dict['address'])
output: suma
----------------------------------------------------------------------
--
KeyError
KeyError: 'address'
get() function:
#another way of acessing keyprint(my_dict.get('year')#if key is not present it will give None using get methodprint(my_dict.get('address')
output: 2020
None
Dict Add or Modify Elements :
Eg:
my_dict={'name':'uma','year':2020,'address':'kadapa'}#update namemy_dict['name']='suma'print(my_dict)#add new keymy_dict['degree']='B.Tech'print(my_dict)
output: {'name':'suma','year':2020,'address':'kadapa'}
{'name':'suma', 'year':2020, 'address':'kadapa' ,'degree':'B.Tech'}
Dict Delete or Remove Element :
Eg:
my_dict={'name':'suma','year':2020,'address':'kadapa'}#remove a particular itemprint(my_dict.pop('year'))print(my_dict)
output: 2020
{'name':'suma','address':'kadapa'}
Eg:
my_dict={'name':'suma','year':2020,'address':'kadapa'}#remove any arbitrary keymy_dict.popitem()print(my_dict)
output: {'name':'suma','year':2020}
Eg:
squares={2:4,3:9,4:16,5:25}del squares[2]print(squares)squares.clear( )print(squares)
output: {3:9,4:16,5:25}
{ }
Eg:
squares={2:4,3:9,4:16}#delete dictionary itselfdel squaresprint(squares)
output: -----------------------------------------------------------
--
NameError
NameError: name 'square' is not defined
Dictionary Methods :
Eg:
squares={2:4,3:9,4:16,5:25}my_dict=squares.copy()print(my_dict)
output: {2:4,3:9,4:16,5:25}
#fromkeys[seq[ ,v]] ->Return a new dictonary with keys from seq and values for all keys is same
subject={ }.fromkeys(['math','english','social'],0)
print(subject)
output: {'math':0,'english':0,'social':0}
Eg:
subjects={2:4,3:9,4:16,5:25}print(subject.items( )) #return a new view of the dictionary items (key,value)
output: dict_items([(2,4),(3,9),(4,16),(5,25)])
Eg:
subject={2:4,3:9,4:16,5:25}print(subject.keys( )) #return a new view of the dictionary keys
output: dict_keys([2,3,4,5])
Eg:
subject={2:4,3:9,4:16,5:25}print(subject.values( )) #return a new view of the dictionary values
output: dict_values([4,9,16,25])
#get list of all available methods and attributes of dictionary
d={ }
print(dir(d))
output: ['__class__','__contain__','__delattr__','__delitem__','__dir__','__doc__','__eq__','__format__','__gr__','__qetattribute__','__getitem__','__gt__','__hash__','__init__','__init_subclass__',''__iter__','__le__','__len__','__lt__,'__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setaattr__','__setitem__','__sizeof__','__str__','__subclasshook__','clear','copy','fromkeys','get','items','keys','pop','popitem','setdefault','update','values']
Dict Comprehension :
Eg:
#dict comprehension are just like list comprehensions but for dictionariesd={'a':1,'b':2,'c':3}for pair in d.items( ):print(pair)
output: ('a',1)
('c',3)
('b',2)
Eg 1:
#Creating a new dictionary with only pairs where the value is larger than 2d={'a':1,'b':2,'c':3,'d':4,'e':5}new_dict={k:v for k,v in d.items( ) if v>2}print(new_dict)
output: {'c':3,'d':4,'e':5}
Eg 2:
d={'a':1,'b':2,'c':3,'d':4}d={k+'c':v*2 for k,v in d.items( ) if v>2}]print(d)
output: {'cc':6,'dc':8,'ec':10}
Comments
Post a Comment