Featured

    Featured Posts

Dictionary In Python Tutorial





§  If we want to represent a group of objects as key-value pairs then we should go for Dictionary.
§  Dictionary is used to storing the information in the form key and value.

§   If you want to maintain information in the form of key and value then we have required to use Dictionary object.

§   A dictionary has a key: value pair. Where each key and value is known as item

§     Both key and value are objects only.

§    Duplicate keys are not allowed but values can be duplicated

§ It allows you to store and retrieve elements by referencing a key. As dictionaries are referenced by key.

Different Ways to Creating a dictionary in Python
ΓΌ   §  Dictionary consists of key-value pairs. It is enclosed by curly braces {}.
     §  A dictionary can be created by enclosing item, separated by commas, in curly braces {} Where item is nothing item is a key-value pair and 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 (,).
     §  keys must be of an immutable data type such as strings, numbers, or tuples.

§  We can create empty dictionary object as follows.

d={}
print(d)
print(type(d))

# The Output Will be
{}
<class 'dict'>

We can create dictionary object with some element If we know data in advance   as follows




d={"name":"john","age":20,"country":"India"}

print(d)

print(type(d))

# The Output Will be

{'name': 'john', 'age': 20, 'country': 'India'}

<class 'dict'>

§  We can create dictionary object with dynamic some element as follows.

d=eval(input("Enter dictionary :"))  

print(d) 

print(type(d)) 

# The Output Will be

Enter Dictionary:{101:'sachin',102:'Vijay',103:'Ajay'}

{101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

<class 'dict'>




§  We can create dictionary object using built-in class: dict()  as follows.

§  The dict() constructor can be used to create dictionaries from keyword arguments, or from a single iterable of key-value pairs, or from a single dictionary and keyword arguments

d = dict()     

print(d) 

print(type(d)) 

# The Output Will be

{}

<class 'dict'>

 

d = dict(a=1, b=2, c=3)  

print(d)

Output:

{'a': 1, 'b': 2, 'c': 3}


d=dict([('a', 1), ('b', 2), ('c', 3)])  

print(d)

Output:

{'a': 1, 'b': 2, 'c': 3}

 

d=dict({'a' : 1, 'b' : 2}, c=3)

print(d)

  Output:

{'a': 1, 'b': 2, 'c': 3}


§  We can create dictionary object using Python Dictionary fromKeys() inbuilt function as follows.

§  Python Dictionary fromKeys() is an inbuilt function that creates a new dictionary from the given sequence of elements .

dictionary.fromkeys(keys, value)

§  This Method takes two parameter first parameter is key that is required parameter.and it is an iterable specifying the keys of the new dictionary.


§  The Second parameter is value parameter that is optional and the value for all keys. The default value is None.

§  Python fromkeys() method returns a new dictionary with a given sequence of elements as the keys of the dictionary.

employees = ['Scott', 'Mark', 'John']

defaults = {'Application Developer', 1000}

resDict = dict.fromkeys(employees, defaults)

      print(resDict)

Output:

{

'Scott': {1000, 'Application Developer'}, '

Mark': {1000, 'Application Developer'}, '

John': {1000, 'Application Developer'}

}

How to access Element from the dictionary

§  The elements of a dictionary can be accessed via a key.

d= {101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

print(d[101])#The OutPut:sachin

print(d[102])#The OutPut:Vijay

print(d[103])#The OutPut:Ajay

    If the specified key is not available then we will get KeyError.

print(d[104])

KeyError: 104


     How We can Avoid KeyError Exceptions

§  One common pitfall when using dictionaries is to access a non-existent key. This typically results in a KeyError exception.

§  One way to avoid key errors is to use the dict.get method, which allows you to specify a default value to return in the case of an absent key.

                    value = mydict.get(key, default_value)

§  Which returns mydict[key] if it exists, but otherwise returns default_value. Note that this doesn't add key to mydict.

 

d={101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

print(d[101])#The OutPut:sachin

print(d[102])#The OutPut:Vijay

print(d[103])#The OutPut:Ajay

print(d.get(104,'Hello'))#The OutPut:Hello


§  In the given example 104 key is not exist if we try to fetch element by using 104 key then we get default value hello because 104 is not key of this given dict. this doesn't add key to dict.

§  if you want to retain that key value pair, you should use mydict.setdefault(key, default_value), which does store the key value pair.

 

d={101: 'sachin', 102: 'Vijay', 103: 'Ajay'}

print(d[101])#The OutPut:sachin

print(d[102])#The OutPut:Vijay

print(d[103])#The OutPut:Ajay

print(d.setdefault(104,'Hello'))#The OutPut:Hello

print(d)

Output:

sachin

Vijay

Ajay

Hello

{101: 'sachin', 102: 'Vijay', 103: 'Ajay', 104: 'Hello'}

§  An alternative way to deal with the problem.

§  You could also check if the key is in the dictionary.

if key in mydict:

    value = mydict[key]

else:

    value = default_value

 

How to Check that given key or given value exists in a dictionary or not

# Create first dictionary

d1={'a':1,'b':2,'c':3}

#Check given key exists in a dictionary

print('a' in d1)#The Output:True

#Another Way Check given key exists in a dictionary

print('a' in d1.keys())#The Output:True

#Check given Value exists in a dictionary

print(2 in d1.values())#The Output:True

 

 

Iterating over a Dictionary

§  You can iterate over the dictionary elements using for loop like below:

for element in dictionary:

       do operation

d = {'a': 1, 'b': 2, 'c':3}

for key in d:

print(key, d[key])

Output:

a 1

b 2

         c 3

 

Nested Dictionary in Python?

§  nested dictionary means defining dictionary inside a dictionary.

 

§   It's a collection of dictionaries into one single dictionary.

 

nested_dict = {

                             'dictA': {'key_1': 'value_1'},

                              'dictB': {'key_2': 'value_2'}

                   }

 

 

§  Here We're going to create dictionary of employee within a dictionary where empId act as a key and employee details dictionary act as a value of dictionary.

 

employees = {
        101: {'name': 'Scott', 'age': '27', 'gender': 'Male'},
        102: {'name': 'Mark', 'age': '22', 'gender': 'Female'},
        103: {'name': 'John', 'age': '30', 'gender': 'Male'},
        104: {'name': 'Peter', 'age': '32', 'gender': 'male'},
        105: {'name': 'Marry', 'age': '33', 'gender': 'Female'},

        }

print(employees)

Output:
{101: {'name': 'Scott', 'age': '27', 'gender': 'Male'}, 102: {'name': 'Mark', 'age': '22', 'gender': 'Female'}, 103: {'name': 'John', 'age': '30', 'gender': 'Male'}, 104: {'name': 'Peter', 'age': '32', 'gender': 'male'}, 105: {'name': 'Marry', 'age': '33', 'gender': 'Female'}}

 

Display Particular Employee Details given by employee id.

employees = {

        101: {'name': 'Scott', 'age': '27', 'gender': 'Male'},

        102: {'name': 'Mark', 'age': '22', 'gender': 'Female'},

        103: {'name': 'John', 'age': '30', 'gender': 'Male'},

        104: {'name': 'Peter', 'age': '32', 'gender': 'male'},

        105: {'name': 'Marry', 'age': '33', 'gender': 'Female'},

        }

 

print(employees)

empid=int(input('enter empId'))

print('Name= ',employees[empid]['name'])

print('Age= ',employees[empid]['age'])

print('Gender= ',employees[empid]['gender'])

Output:
{101: {'name': 'Scott', 'age': '27', 'gender': 'Male'}, 102: {'name': 'Mark', 'age': '22', 'gender': 'Female'}, 103: {'name': 'John', 'age': '30', 'gender': 'Male'}, 104: {'name': 'Peter', 'age': '32', 'gender': 'male'}, 105: {'name': 'Marry', 'age': '33', 'gender': 'Female'}}
enter empId101
Name=  Scott
Age=  27
Gender=  Male

Display ALl Employee Details .

employees = {
        101: {'name': 'Scott', 'age': '27', 'gender': 'Male'},
        102: {'name': 'Mark', 'age': '22', 'gender': 'Female'},
        103: {'name': 'John', 'age': '30', 'gender': 'Male'},
        104: {'name': 'Peter', 'age': '32', 'gender': 'male'},
        105: {'name': 'Marry', 'age': '33', 'gender': 'Female'},

        }

 
print(employees)
 
for empid in range(101,106):
    print('Name= ',employees[empid]['name'])
    print('Age= ',employees[empid]['age'])
    print('Gender= ',employees[empid]['gender'])
    print("====================================")
Output:
Name=  Scott
Age=  27
Gender=  Male
====================================
Name=  Mark
Age=  22
Gender=  Female
====================================
Name=  John
Age=  30
Gender=  Male
====================================
Name=  Peter
Age=  32
Gender=  male
====================================
Name=  Marry
Age=  33
Gender=  Female
====================================

Access the value of key ‘history’ in given Dictionary
sampleDict = {
   "class":{
      "student":{
         "name":"Mike",
         "marks":{
            "physics":70,
            "history":80
         }
      }
   }
}
 
print(sampleDict['class']['student']['marks']['history'])
Output:
80
 
How to update dictionaries?
 
d[key]=value 
§    If the key is not available then a new entry will be added to the dictionary with the specified key-value pair.
 
§  If the key is already available then old value will be replaced with new value.
d1={'a':1,'b':2,'c':3}
print("Before Update= ",d1)
#Update the c key value
d1['c']=4
print('After Update= ',d1)
Output:
Before Update=  {'a': 1, 'b': 2, 'c': 3}
After Update=  {'a': 1, 'b': 2, 'c': 4}



Python Dictionary Methods

d.items()
§  d.items() returns a list of tuples containing the key-value pairs in d. The first item in each tuple is the key, and the second item is the key’s value:
 
§  The items () method can be used to loop over both the key and value simultaneously:
 
d = {'a': 1, 'b': 2, 'c':3}
print(d.items())
for key,value in d.items():
    print(key, value)
Output:
dict_items([('a', 1), ('b', 2), ('c', 3)])
a 1
b 2
c 3
 
d.values()
§  Returns a list of values in a dictionary.
§  values () method can be used to iterate over only the values, as would be expected.
d = {'a': 1, 'b': 2, 'c':3}
print(d.values())
for value in d.values():
    print(value)
Output:
dict_values([1, 2, 3])
1
2
3
Any duplicate values in d will be returned as many times as they occur:
d = {'a': 1, 'b': 1, 'c':1}
print(d.values())
for value in d.values():
    print(value)
Output:
dict_values([1, 1, 1])
1
1
1
d.keys()
§  Returns a list of keys in a dictionary.
§  keys() method can be used to iterate over only the keys as would be expected.
 
d = dict(a=1, b=2, c=3)  
print(d.keys())
for key in d.keys():
    print(key)
Output:
dict_keys(['a', 'b', 'c'])
a
b
c
d.pop(key)
§  You can remove entry associated with the specified key with the help of pop method.
 
§  This method removes the entry by specified key and returns corresponding value.
 
§  If the specified key is not present then we will get KeyError .
d = {'a': 1, 'b': 1, 'c':1
print('Deleted Item =',d.pop('a'))
print(d)
Output:
Deleted Item = 1
{'b': 1, 'c': 1}
print('Deleted Item =',d.pop('d'))
KeyError: 'd'
 

Write a python program to check whether the given key is present, if present print the value , else add a new key and value
 
d={101:'John',102:'Harry',103:'Scott',104:'Marry',105:'Peter'}
key=int(input('enter key'))
print('Original Dictionary =',d);
value=d.setdefault(key,'Clerk')
print("Value="+value);
print('Update Dictionary =',d);


Both Dictionary Having Unique Values

If all the values ​​are different in both dictionary, then the second dictionary value will be appended in the first dictionary, value.

dict1.update(dict2)

# Create first dictionary
d1={'a':1,'b':2,'c':3}
# Create second dictionary
d2={'d':4,'e':5,'f':6}
print("Before Merging Both Dictionary")
print("d1= ",d1)
print("d2= ",d2)
print("===========================")
# Merge contents of dict2 in dict1
d1.update(d2)
print("After Merging Both Dictionary")
print("d1= ",d1)
print("d2= ",d2)
Another important point to notice is that, we didn’t got a new dictionary. The contents of dict1 changed
 
If both dictionary. having the same common key , then the first  dictionary key value will be replaced by the second dictionary key value.
dict1.update(dict2)
# Create first dictionary
d1={'a':1,'b':2,'c':3}
# Create second dictionary
d2={'d':4,'a':5,'f':6}
print("Before Merging Both Dictionary")
print("d1= ",d1)
print("d2= ",d2)
print("===========================")
# Merge contents of dict2 in dict1
d1.update(d2)
print("After Merging Both Dictionary")
print("d1= ",d1)
print("d2= ",d2)
 
Output:
Before Merging Both Dictionary
d1=  {'a': 1, 'b': 2, 'c': 3}
d2=  {'d': 4, 'a': 5, 'f': 6}
===========================
After Merging Both Dictionary
d1=  {'a': 5, 'b': 2, 'c': 3, 'd': 4, 'f': 6}

d2=  {'d': 4, 'a': 5, 'f': 6}


How can merge two Python dictionaries in a single expression?

Using the (**) Operator

§  Starting in Python 3.5, the double asterisk can be used to unpack a dictionary.
§  we can merge the two dictionaries in a single expression.

 

dict1={}

dict2={}

dict3= {**dict1, **dict2}

 

 

# Create first dictionary

d1={'a':1,'b':2,'c':3}

# Create second dictionary

d2={'d':4,'a':5,'f':6}

print("Before Merging Both Dictionary")

print("d1= ",d1)

print("d2= ",d2)

print("===========================")

# Merge contents of dict2 in dict1

d3={**d1,**d2}

print("After Merging Both Dictionary")

print("d1= ",d1)

print("d2= ",d2)

print("d3= ",d3)

 

Output:

Before Merging Both Dictionary

d1=  {'a': 1, 'b': 2, 'c': 3}

d2=  {'d': 4, 'a': 5, 'f': 6}

===========================

After Merging Both Dictionary

d1=  {'a': 1, 'b': 2, 'c': 3}

d2=  {'d': 4, 'a': 5, 'f': 6}

d3=  {'a': 5, 'b': 2, 'c': 3, 'd': 4, 'f': 6}


Converting two lists into the Dictionary


list1=[1,2,3,4,5]

list2=['One','Two','Three','Four','Five']

dict1=  dict(zip(list1, list2))

print(dict1)






















author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews