Python Dictionary - shahzade baujiti

Breaking

Wednesday, April 24, 2019

Python Dictionary

Python Dictionary

Dictionary is an unordered set of key and value pair. It is a container that contains data, enclosed within curly braces.The pair i.e., key and value is known as item. The key passed in the item must be unique.

The key and the value is separated by a colon(:). This pair is known as item. Items are separated from each other by a comma(,). Different items are enclosed within a curly brace and this forms Dictionary.

Python Dictionary Example
data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'} 
print data  

Output:
>>>
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
>>>


Note:
Dictionary is mutable i.e., value can be updated.
Key must be unique and immutable. Value is accessed by key. Value can be updated while key cannot be changed.
Dictionary is known as Associative array since the Key works as Index and they are decided by the user.

Python Dictionary Example
plant={} 
plant[1]='Ravi' 
plant[2]='Manoj' 
plant['name']='Hari' 
plant[4]='Om' 
print plant[2] 
print plant['name'] 
print plant[1] 
print plant  

Output:
>>>
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}
>>>

Accessing Dictionary Values
Since Index is not defined, a Dictionary values can be accessed by their keys only. It means, to access dictionary elements we need to pass key, associated to the value.

Python Accessing Dictionary Element Syntax
<dictionary_name>[key] 
</dictionary_name> 

Accessing Elements Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'} 
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'} 
print "Id of 1st employer is",data1['Id'] 
print "Id of 2nd employer is",data2['Id'] 
print "Name of 1st employer:",data1['Name'] 
print "Profession of 2nd employer:",data2['Profession'] 

Output:
>>>
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer
>>>

Updating Python Dictionary Elements
The item i.e., key-value pair can be updated. Updating means new item can be added. The values can be modified.

Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'} 
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'} 
data1['Profession']='Manager' 
data2['Salary']=20000 
data1['Salary']=15000 
print data1 
print data2 

Output:
>>>
{'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}
>>>

Deleting Python Dictionary Elements Example
del statement is used for performing deletion operation.
An item can be deleted from a dictionary using the key only.

Delete Syntax
1.    del  <dictionary_name>[key] 
2.    </dictionary_name> 

Whole of the dictionary can also be deleted using the del statement.

Example
data={100:'Ram', 101:'Suraj', 102:'Alok'} 
del data[102] 
print data   
del data 
print data 
#will show an error since dictionary is deleted. 


Output:
>>>
{100: 'Ram', 101: 'Suraj'}

Traceback (most recent call last):
         File "C:/Python27/dict.py", line 5, in
          print data
NameError: name 'data' is not defined
>>>

Python Dictionary Functions and Methods
Python Dictionary supports the following Functions

Python Dictionary Functions

Functions
Description
len(dictionary)
It returns number of items in a dictionary.
cmp(dictionary1,
dictionary2)
It compares the two dictionaries.
str(dictionary)
It gives the string representation of a string.

Python Dictionary Methods

Methods
Description
keys()
It returns all the keys element of a dictionary.
values()
It returns all the values element of a dictionary.
items()
It returns all the items(key-value pair) of a dictionary.
update(dictionary2)
It is used to add items of dictionary2 to first dictionary.
clear()
It is used to remove all items of a dictionary. It returns an empty dictionary.
fromkeys(sequence,value1)
/ fromkeys(sequence)
It is used to create a new dictionary from the sequence where sequence elements forms the key and all keys share the values ?value1?. In case value1 is not give, it set the values of keys to be none.
copy()
It returns an ordered copy of the data.
has_key(key)
It returns a boolean value. True in case if key is present in the dictionary ,else false.
get(key)
It returns the value of the given key. If key is not present it returns none.

Python Dictionary len(dictionary) Example
It returns length of the dictionary.

data={100:'Ram', 101:'Suraj', 102:'Alok'} 
print data 
print len(data) 

Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
3
>>>

Python Dictionary cmp(dictionary1,dictionary2) Example
The comparison is done on the basis of key and value.

If, dictionary1 == dictionary2, returns 0. 
      dictionary1 < dictionary2, returns -1. 
     dictionary1 > dictionary2, returns 1. 
data1={100:'Ram', 101:'Suraj', 102:'Alok'} 
data2={103:'abc', 104:'xyz', 105:'mno'} 
data3={'Id':10, 'First':'Aman','Second':'Sharma'} 
data4={100:'Ram', 101:'Suraj', 102:'Alok'} 
print cmp(data1,data2) 
print cmp(data1,data4) 
print cmp(data3,data2) 

Output:
>>>
-1
0
1
>>>

Python Dictionary str(dictionary) Example
This method returns string formation of the value.

data1={100:'Ram', 101:'Suraj', 102:'Alok'} 
print str(data1) 

Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
>>>

Python Dictionary keys() Method Example
This method returns all the keys element of a dictionary.

data1={100:'Ram', 101:'Suraj', 102:'Alok'} 
print data1.keys() 

Output:
>>>
[100, 101, 102]
>>>

Python Dictionary values() Method Example
This method returns all the values element of a dictionary.

data1={100:'Ram', 101:'Suraj', 102:'Alok'} 
print data1.values() 

Output:
>>>
['Ram', 'Suraj', 'Alok']
>>>

Python Dictionary items() Method Example
This method returns all the items(key-value pair) of a dictionary.

data1={100:'Ram', 101:'Suraj', 102:'Alok'} 
print data1.items() 

Output:
>>>
[(100, 'Ram'), (101, 'Suraj'), (102, 'Alok')]
>>>

Python Dictionary update(dictionary2) Method Example
This method is used to add items of dictionary2 to first dictionary.

data1={100:'Ram', 101:'Suraj', 102:'Alok'} 
data2={103:'Sanjay'} 
data1.update(data2) 
print data1 
print data2 

Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok', 103: 'Sanjay'}
{103: 'Sanjay'}
>>>

Python Dictionary clear() Method Example
It returns an ordered copy of the data.

data1={100:'Ram', 101:'Suraj', 102:'Alok'} 
print data1 
data1.clear() 
print data1 

Output:
>>>
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
{}
>>>

Python Dictionary fromkeys(sequence)/ fromkeys(seq,value) Method Example
This method is used to create a new dictionary from the sequence where sequence elements forms the key and all keys share the values ?value1?. In case value1 is not give, it set the values of keys to be none.

sequence=('Id' , 'Number' , 'Email') 
data={} 
data1={} 
data=data.fromkeys(sequence) 
print data 
data1=data1.fromkeys(sequence,100) 
print data1 

Output:
>>>
{'Email': None, 'Id': None, 'Number': None}
{'Email': 100, 'Id': 100, 'Number': 100}
>>>

Python Dictionary copy() Method Example
This method returns an ordered copy of the data.

data={'Id':100 , 'Name':'Aakash' , 'Age':23} 
data1=data.copy() 
print data1 

Output:
>>>
{'Age': 23, 'Id': 100, 'Name': 'Aakash'}
>>>

Python Dictionary has_key(key) Method Example
It returns a boolean value. True in case if key is present in the dictionary, else false.

data={'Id':100 , 'Name':'Aakash' , 'Age':23} 
print data.has_key('Age') 
print data.has_key('Email') 

Output:
>>>
True
False
>>>

Python Dictionary get(key) Method Example
This method returns the value of the given key. If key is not present it returns none.

data={'Id':100 , 'Name':'Aakash' , 'Age':23} 
print data.get('Age') 
print data.get('Email') 

Output:
>>>
23
None
>>>

No comments:

Post a Comment