Dictionary in Python


What is Dictionary ?

Dictionaries are another mutable data structure.

  • A dictionary is a set of unordered key, value pairs.

  • Each entry in dictionary having two elements, key and value.

  • Key and value is separated by : (colon)

  • Keys are unique in , value may be duplicate.

  • The values of dictionary can be of any type, but the keys are must be of an immutable data type such as string, numbers, or tuples.

  • The whole thing is enclosed within curly braces { }

How to create Dictionary ?

Dictionary creation is very simple in python, just place the items inside the curly braces { } separated by comma.

An item is represented by the pair of key and the corresponding value, key : value.

Value can be duplicate but key must be unique and immutable.

#Create an empty dictionary
my_dict = {}
   OR
my_dict = dict()

print(type(d))

[OUTPUT]
<class 'dict'>

#Create Dictionary with entries:

SYNTAX:

my_dict = { <key> : <value>, <key> : <value>, . . . <key> : <value> }

Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.

The following defines a dictionary that maps a country to its corresponding capital


capitals = {
    'India':'New Delhi',
    'Russia':'Moscow',
    'USA':'Washington',
    'Srilanka':'Colombo',
    'China':'Beijing'
      }                    
                

As we can see in the above example, one entry consist two things, first a key and second value separated by : (colon). Each key is associated with a value.

In Python's dictionaries operations like add,update,delete of entries are done by the keys.

Example:

#Dictionary of person's age
>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> print(person_age)
{'John': 21, 'Kim': 35, 'Alex': 26}
# accessing using key
>>> print(person_age['Kim'])
35

# update using key
>>> person_age['Kim'] = 30
>>> print(person_age['Kim'])
30

# adding new element
>>> person_age['Steve'] = 32
>>> print(person_age)
{'John': 21, 'Kim': 30, 'Alex': 26, 'Steve': 32}
                

New element will be added only if the key is unique else this operation will update the existing key's value.
Consider the example below....

#Dictionary of person's age
>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> print(person_age)
{'John': 21, 'Kim': 35, 'Alex': 26}

# adding new element
>>> person_age['Steve'] = 32
>>> print(person_age)
{'John': 21, 'Kim': 30, 'Alex': 26, 'Steve': 32}

As we can see new element 'Streve' is added

#adding new element >>> person_age['Kim'] = 50 >>> print(person_age) {'John': 21, 'Kim': 50, 'Alex': 26, 'Steve': 32}

Since 'Kim' key is alredy exist, it will perform the updation operation.

In short we can say that, if we perform the assignment operation, if the key is not the part of dictionary, addition operation will take place otherwise updation.

Access elements from Dictionary:

To access the value from dictionary we use key as index, so there are two ways to perform this operation, first pass the key inside the square bracket [] or inside the get( ) method.

The difference between both is, if the key is not found then get( ) method gives None as output while other one raise a KeyError.

                            
>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> print(person_age['Kim'])
35
>>> print(person_age.get('Kim'))
35
#Pass a key which is not in dictionary
>>> print(person_age['xyz'])
Traceback (most recent call last):
  File "<pyshell#104>", line 1, in <module>
    print(person_age['xyz'])
KeyError: 'xyz'

>>> print(person_age.get('xyz'))
None 
        

The beauty of get( ) method is, if you don't want None as ouput you can print custom message tho the user.

                            
>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
#Pass the custom message as second argument                      
>>> print(person_age.get('xyz','Key is not found'))
Key is not found
                  

Delete elements from Dictionary:

To delete items from dictionary we can use methods pop(), popitem(), clear() and the keyword del.

1. pop() method removes an item with the provided key and returns the value.

This method raise a KeyError, if key is not found.


>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> print(person_age.pop('Kim'))
35
>>> print(person_age)
{'John': 21, 'Alex': 26}
                
                 

2. popitem() method removes an arbitrary entry and returns the value.

This method raise a KeyError, if dictionary is empty.


>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> print(person_age.popitem())
('Alex', 26)
>>> print(person_age)
{'John': 21, 'Kim': 35}
                
                

3. clear() method removes all the items.


>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> person_age.clear()
>>> print(person_age)
{}
                
                

4. del keyword delete the dictionary.


>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> del person_age.clear()
>>> print(person_age)
Traceback (most recent call last):
  File "<pyshell#117>", line 1, in <module>
    print(person_age)
NameError: name 'person_age' is not defined
                        

Dictionary Methods with Example:

Some methods of dictionary have been already discussed above. Some more methods with example is given below...

1. update(), if the key is present updates the value else add key to dictionary.

>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> person_age.update({'Harry':25})
>>> print(person_age)
{'John': 21, 'Kim': 35, 'Alex': 26, 'Harry': 25}
                        

2. setdefault(), Set dict[key]=default if key is not already in dict.

>>>person_age = {
    "John":21,
    "Kim":35,
    "Alex":26
    }
>>> person_age.setdefault('Syam',30)
30
>>> print(person_age)
{'John': 21, 'Kim': 35, 'Alex': 26, 'Syam': 30}

#returns None and key added to dictionary with value--None
>>> person_age.setdefault('Alice')
>>> print(person_age)
{'John': 21, 'Kim': 35, 'Alex': 26, 'Syam': 30, 'Alice': None}
                        

3. keys(), returns all the keys from dictionary as dict_keys object.

>>> k = person_age.keys()
>>> type(k)
<class 'dict_keys'>
>>> print(k)
dict_keys(['John', 'Kim', 'Alex', 'Syam', 'Alice'])
>>>
                        

4. values(), returns all the values from dictionary as dict_values object.

>>> v = person_age.values()
>>> print(v)
dict_values([21, 35, 26, 30, None])
>>> type(v)
<class 'dict_values'>
>>>
                        

5. items(), returns the items from dictionary as dict_items object.

>>> i = person_age.items()
>>> print(i)
dict_items([('John', 21), ('Kim', 35), ('Alex', 26), ('Syam', 30), ('Alice', None)])
>>> type(i)
<class 'dict_items'>
>>>
                        

Converting the dict_keys, dict_values and dict_items to list.

>>> l = list(x)
>>> print(l)
['John', 'Kim', 'Alex', 'Syam', 'Alice']
>>> l1 = list(v)
>>> print(l1)
[21, 35, 26, 30, None]
>>> l2 = list(i)
>>> print(l2)
[('John', 21), ('Kim', 35), ('Alex', 26), ('Syam', 30), ('Alice', None)]
>>>                                    
                                

6. fromkeys(seq[, v]), Creates dictionary from the sequence of immutable objects as key and the value equal to v.If we don't pass the value v, default None is assigned.

>>> l = ['ram', 23.67, ('shyam', 67)]
>>> dt = {}
>>> dt = dt.fromkeys(l)
>>> print(dt)
{'ram': None, 23.67: None, ('shyam', 67): None}
>>> dt = dt.fromkeys(l, -2)
>>> print(dt)
{'ram': -2, 23.67: -2, ('shyam', 67): -2}
>>>
                        

Sorting Dictionary:

#Create dictionary
>>> dt = {'John': 21, 'Kim': 35, 'Alex': 26, 'Syam': 30, 'Alice': 34}

#returns sorted list of key
>>> l  = sorted(dt)
>>> print(l)
['Alex', 'Alice', 'John', 'Kim', 'Syam']

#returns list of key
>>> l = sorted(dt.keys())
>>> print(l)
['Alex', 'Alice', 'John', 'Kim', 'Syam']

#returns list of values
>>> l = sorted(dt.values())
>>> print(l)
[21, 26, 30, 34, 35]

#returns list of sorted key value pair based on key
>>> l = sorted(dt.items())
>>> print(l)
[('Alex', 26), ('Alice', 34), ('John', 21), ('Kim', 35), ('Syam', 30)]

#sort dictionary on values
>>> l = sorted(dt.items(), key = lambda x:x[1])
>>> print(l)
[('John', 21), ('Alex', 26), ('Syam', 30), ('Alice', 34), ('Kim', 35)]

#sort dictionary on keys
>>> l = sorted(dt.items(), key = lambda x:x[0])
>>> print(l)
[('Alex', 26), ('Alice', 34), ('John', 21), ('Kim', 35), ('Syam', 30)]
>>>
                             

Iterating Through a Dictionary

>>> for i in dt:
	print("%s %s"%(i,dt[i]))

John 21
Kim 35
Alex 26
Syam 30
Alice 34

#another way to iterate
>>> for index, value in enumerate(dt):
	 print (index, value , dt[value])

	 
0 John 21
1 Kim 35
2 Alex 26
3 Syam 30
4 Alice 34
>>>

#another way to iterate
>>> for i in dt.keys():
	print(i, dt[i])

	
John 21
Kim 35
Alex 26
Syam 30
Alice 34
                        
#another way to iterate
>>> for k,v in dt.items():
	print(k, v)

	
John 21
Kim 35
Alex 26
Syam 30
Alice 34
>>>
                        

Dictionary Membership Test:

For Dictionaries, x in dict cheks to see whether x is a key in the dictionary.

>>> 'Jhon' in dt
False

>>> 'John' in dt
True
>>>
   

Built-in Functions:

Built-in functions all(), any(), len(), sorted() etc can also use with dictionary.

#all() returns True if all the 
#keys are true or dictionary is empty.
>>> all(dt)
True

#any() returns True if any key
#is true, False if dictionary is empty.
>>> any(dt)
True

#len() returns the length
>>> len(dt)
5
                      


Python Dictionary Comprehension:

Dictionary comprehension is a way to create new dictionary from an iterable in python.

Dictionary comprehension consist of an expression with pair (key:value) followed by for loop inside the curly braces { }.


>>> sqr = {x : x*x for x in range(1,6)}
>>> print(sqr)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}                          
                      

The above code is equivalent to

>>> sqr = { }
>>> for x in range(1,6):
	sqr[x] = x*x

>>> print(sqr)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}                          
                      

Dictionary comprehension can also consist conditional statement to make filter.

Create a dictionary of cubes of even numbers from 1 to 10.


>>> cube = {x : x*x*x for x in range(1,10) if (x%2==0) }
>>> print(cube)
{2: 8, 4: 64, 6: 216, 8: 512}
                      

Next chapter is Python Array






 

Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved