All About Python Dictionary – Introduction, Basic Operations, Inbuilt Methods

 

 

Dictionary in Python

In this tutorial we are going about the basics of  dictionary , how to  create it, how can we access it  and what are the  operations that can be performed on it.

Python dictionary is an unordered collection of items.  it has key : value pairs therefore here key should be unique & immutable. Values in a dictiionary can be of any datatype and can be duplicated, whereas keys cannot be repeat.

dictionary-tuple-list

How to create a dictionary

  • Dictionary can also be create by  built-in function dict().
  • Dictionary keys are case sensitive .

Accessing  values using keys

we can access dictiionary values using the key as follows – pass key as Index to the dictionary this will print the value for that particular key, this is direct lookup –

 

 

How to add keys/values to the Dictionary

We can add new items or update existing items by using either assignment operator or using Python built-in method update( ).

 

 

How to find the length of a Python Dictionary

we can find length using len( ) function in python .

>>>a={1:’G’,2:’M’,3:’T’,4:’B’}

>>>print(len(a))

>>>4

How to remove items from a  Dictionary

  • pop(key): removes the items with provided key and returns its value to output console
  • popitem(key): same as pop(), the difference being that popitem() removes the random item and returns the (key,value) pair in the output console
  • del: deletes a single item or the dictiionary entirely
  • clear(): clears all the items in the dictionary and returns an empty dictiionary

>>> dict = {1:’a’,2:’b’,3:’c’,4:’d’,5:’e’}

>>>> dict.pop(1) #Remove an item from dictiionary using pop()

>>>a’

>>> print (dict)

>>>{2:’b’,3:’c’,4:’d’,5:’e’}

>>> dict.popitem() #Remove an item using popitem()

>>>(5,’e’)

>>> print (dict)

>>>{2,’b’,3:’c’,4:’d’}

>>> del dict[2] #deletes item with key 2

>>> print (dict)

>>>{3:’c’,4:’d’}

>>> dict.clear() #Remove all item using clear()

>>> print (py_dict) #this will return empty dictiionary

>>>{}

How to Iterate through a Python Dictionary

it can be done using loops in python

>>>dict = {1:’a’,2:’b’,3:’c’,4:’d’}

>>>for x in py_dict:

print (dict[x])
>>>a
b
c
d

How to find Maximum and Minimum value in Python Dictionary

>>> dt = {1:111,2:212,3:333}

>>> kmax = max(dt.keys(), key=(lambda x: dt[x]))             #To find the key of max and min value
>>> print (kmax)
>>>3
>>> print (dt[kmax])                                                           #print max value
>>>333
>>> kmin = min(dt.keys(), key=(lambda y: dt[y]))
>>> print (kmin)
>>>1
>>> print (dt[kmin])                                                           #print min value
>>>111

>>> kmax = max(py_dict, key = lambda m: dt[m])

>>> kmin = min(py_dict, key = lambda n: dt[n])
>>> print (dt[kmax])                                                             #print max value
>>>333
>>> print (dt[kmin])                                                             #print min value
>>>111

How to Concatenate Two Python Dictionaries

>>> d1 = {1:2,2:3}
>>> d2 = {3:4,4:5}

>>> d3 = dict(d1.items() + d2.items())
>>> print (d3)
>>>{1:2,2:3,3:4,4:5}

>>> d4 = {} #declaring a empty dictionary first
>>> for x in (d1,d2): d4.update(x)
>>> print (d4)
>>>{1:2,2:3,3:4,4:5}

Python Dictionary Inbuilt Methods

  • dict.clear( ) :- Removes all the items .
  • dict.copy( ):- Return the shallow copy of a dictiionary.
  • dict.fromkeys(seq[, value] ):- Create a new dictiionary with keys from seq and values set to value.
  • dict.get(key ):- It returns corresponding value of key key . If key doesn’t exist, then it returns none.
  • dict.has_key(key):- Returns true if ‘key’ exist in the dictiionary.
  • dict.items( ):- Returns a new view of dictionary items.
  • dict.keys( ):- Returns the list of keys in the dictiionary.
  • dict.pop(key):- Removes the items with key and returns the value to console. If the key doesn’t exist in the dictiionary, it raises a TypeError.
  • dict.popitem( ):- Removes an arbitrary item in the diictionary and return it to console.
  • dict.setdefault(key[, v]):- Returns corresponding value if the key exists already, else it inserts new key into the dictionary with the value of ‘v’ If v is empty, then value defaults to none.
  • dict.update(dict_x):- Updates the dictiionary dict’s key/value pairs with that of from dict_x.
  • dict.values( ):- Returns the list of values of dictinary dict.

Few examples  of Above Methods

>>>marks = {}.fromkeys([‘Math’,’English’,’Science’], 0)

>>> {‘English’: 0, ‘Math’: 0, ‘Science’: 0}

>>>print(marks)

>>>for item in marks.items():

print(item)

>>>  [‘English’, ‘Math’, ‘Science’]

>>>list(sorted(marks.keys()))

>>> [‘English’, ‘Math’, ‘Science’]

Dictionary Comprehension

>>>squares = {x: x*x for x in range(6)}

>>>print(squares)

>>> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

How to convert a List of Tuples into Dictionary

>>>def Convert(tup, di): 

for a, b in tup:
di.setdefault(a, []).append(b)
return di

tup = [(“akash”, 10), (“gaurav”, 12), (“anand”, 14), (“suraj”, 20), (“akhil”, 25), (“ashish”, 30)]
di = {}
print (Convert(tup, di))

>>{‘akash’: [10], ‘gaurav’: [12], ‘anand’: [14], ‘ashish’: [30], ‘akhil’: [25], ‘suraj’: [20]}

Referenced Sources :  http://www.geeksforgeeks.org ,https://docs.python.org

Tags: Dictiionary with its introduction , how to create it, how to access it and explanation about the various methods that are explained, python dictionaries, python operations, tuple vs dictiionary in python, dictionary operations in python, add element in python dictiionary, remove element from python dictionary,python dictiionary examples, python pop.

%d bloggers like this: