Search This Blog

Wednesday, 15 December 2021

Dictionary in Python

 

Python Dictionary

free simple website templates

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.

dict = { }  #empty dictionary
dict = {1:'Python',2:'Java',3:'C++'}
  • 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.

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

syntax : 

<dictionary_name>[key]      

dict = {1:'Python',2:'Java',3:'C++','c': 'Gods language'}
print(dict[1])
print(dict['c'])

output : 

Python
Gods language

iterate all elemnet using for loop for keys() method, keys() method return list of all keys in dictionary.

dict = {1:'Python',2:'Java',3:'C++','c': 'Gods language'}
print(dict.keys())
for x in dict.keys():
    print(dict[x])

output : 

dict_keys([1, 2, 3, 'c'])
Python
Java
C++
Gods language

If we attempt to access a data item with a key, which is not a part of the dictionary, we get an error as follows −

dict = {1:'Python',2:'Java',3:'C++','c': 'Gods language'}
print(dict[4])

output of above example  :

Traceback (most recent call last):
  File "main.py", line 9, in < module>
    print(dict[4])
KeyError: 4

Updating Dictionary Elements

You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown in a simple example given below

dict = {1:'Python',2:'Java',3:'C++'}
dict[3]="C#"
dict[4]="PHP" #insert new value
print(dict)

output of above example  :

{1: 'Python', 2: 'Java', 3: 'C#', 4: 'PHP'}

Deleting Dictionary Elements 

del statement is used for performing deletion operation.  An item can be deleted from a dictionary using the key only. To explicitly remove an entire dictionary, just use the del statement. Following is a simple example -

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
del dict[3] # remove entry with key 'Name'
print(dict)

dict.clear() # remove all entries in dict
print("dict : ",dict)

del dict # delete entire dictionary
print(dict[2])

output of above example  :

{1: 'Python', 2: 'Java', 4: 'PHP'}
dict : {}
Traceback (most recent call last):
  File "main.py", line 17, in
    print(dict[2])
TypeError: 'type' object is not subscriptable

Built-in Dictionary Functions and Methods

dictionary function

fundescription
cmp(dict1, dict2)No longer available in Python 3.
len(dict)Gives the total length of the dictionary.
This would be equal to the number
of items in the dictionary.
str(dict)Produces a printable string
representation of a dictionary
type(variable)Returns the type of the passed variable.
If passed variable is dictionary,
then it would return a dictionary type.

dictionary methods

methoddescription
dict.clear()Removes all elements of dictionary dict
dict.copy()Returns a shallow copy of dictionary dict
dict.fromkeys()Create a new dictionary with keys
from seq and values set to value.
dict.get(key, default=None)For key key, returns value
or default if key not in dictionary
dict.has_key(key)Removed, use the in operation instead.
dict.items()Returns a list of dict's (key, value) tuple pairs
dict.keys()Returns list of dictionary dict's keys
dict.setdefault(key, default = None)Similar to get(), but
will set dict[key] = default
if key is not already in dict
dict.update(dict2)Adds dictionary dict2's
key-values pairs to dict
dict.values()Returns list of dictionary dict's values
  • len(dict) - The method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
print(len(dict))

output of above example  :

4
  • str(dict) - The method str() produces a printable string representation of a dictionary.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
print(str(dict))

output of above example  :

{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
  • type() - The method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
print(type(dict))

output of above example  :

<class 'dict'>
  • clear() - The method clear() removes all items from the dictionary.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

print(str(dict))
dict.clear()
print(str(dict))

output of above example  :

{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
{}
  • copy() - The method copy() returns a shallow copy of the dictionary.

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
dict2=dict1.copy()
print(dict2)

output of above example  :

{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
  • fromkeys() - The method fromkeys() creates a new dictionary with keys from seq and values set to value.

dict.fromkeys(seq[, value]))

Example :

seq = ('java', 'python', 'c++')
dict = dict.fromkeys(seq)

print ("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 50)
print ("New Dictionary : %s" % str(dict))

output of above example  :

New Dictionary : {'python': None, 'java': None, 'c++': None}
New Dictionary : {'python': 50, 'java': 50, 'c++': 50}
  • itmes() - The method items() returns a list of dict's (key, value) tuple pairs.

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
print(dict1.items())

output of above example  :

dict_items([(1, 'Python'), (2, 'Java'), (3, 'C++'), (4, 'PHP')])
  • keys() - The method keys() returns a list of all the available keys in the dictionary.

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
all_keys=dict1.keys()
print(all_keys)

output of above example  :

dict_keys([1, 2, 3, 4])
  • update() - The method update() adds dictionary dict2's key-values pairs in to dict. This function does not return anything.

dict.update(dict2)

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
dict2= {1: 'Python3',5:'C'} #update Python to Python3
dict1.update(dict2)
print(dict1)

output of above example  :

{1: 'Python3', 2: 'Java', 3: 'C++', 4: 'PHP', 5: 'C'}
  • value() - The method values() returns a list of all the values available in a given dictionary.

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}
values= dict1.values()
print(values)

output of above example  :

dict_values(['Python', 'Java', 'C++', 'PHP'])
  • setdefault() - The method setdefault() is similar to get(), but will set dict[key] = default if key is not already in dict.

dict.setdefault(key, default = None)

  • key − This is the key to be searched. 
  • default − This is the Value to be returned in case key is not found. 

output of above example  :

dict={'emp_name':'Vishal','age':21,'emp_id':101}
dict.setdefault('company','apkzube')
print(dict['emp_name'])
print(dict['company'])

output of above example  :

Vishal
ApkZube

how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...