top

Search

Python Tutorial

Python’s dictionary is also a collection type object. However, unlike list or tuple, it is not a sequence. It is a mapping type object. Dictionary is an unordered collection of comma separated key-value pairs. Key is mapped to its value by special hashing mechanism of Python interpreter. Association of key to value is marked by : symbol between them.Some examples of dictionary objects are shown below:In [1]: capitals={"Maharashtra":"Mumbai", "Telangana":"Hyderabad", "Tamilnadu":"Chennai", "Karnataka":"Bengaluru", "Bihar":"Patna"} rankings={1:"India", 2:"England", 3:"South Africa", 4:"Australia", 5:"New Zealand"} prices={"pen":25, "bike":50000, "mobile": 5000,"book": 250 } In [2]: print ("state capitals:", capitals) print ("Team rankings:", rankings) print ("prices:",prices) Out[2]: state capitals: {'Maharashtra': 'Mumbai', 'Telangana': 'Hyderabad', 'Tamilnadu': 'Chennai', 'Karnataka': 'Bengaluru', 'Bihar': 'Patna'} Team rankings: {1: 'India', 2: 'England', 3: 'South Africa', 4: 'Australia', 5: 'New Zealand'} prices: {'pen': 25, 'bike': 50000, 'mobile': 5000, 'book': 250}Key should be an immutable object. Number, string or tuple can be used as key in dictionary. Use of mutable object as key will raise TypeError. Any object is valid for use as value.In [3]: manufacturers={("Nokia", "Samsung","MicroMax"):"Mobiles", ("Nike", "Adidas", "Puma"):"Sports Goods",               ("Honda","Bajaj", "TVS"):"Bikes"} sports={"indoors":["chess", "Badminton", "Table Tennis"], "outdoor":["Cricket", "Football", "Rugby"]} In [4]: animals={["snake", "Lizard"]:"reptiles", ["Parrot", "Crow"]:"birds"} --------------------------------------------------------------------------- TypeError                                Traceback (most recent call last) <ipython-input-4-1904d3d80b08> in <module>() ----> 1 animals={["snake", "Lizard"]:"reptiles", ["Parrot", "Crow"]:"birds"} TypeError: unhashable type: 'list'Same Key doesn’t appear more than once in one collection. One value can be assigned to more than one keys. If key is used more than once, only the last will be retained.In [5]: marks={"Laxman":56, "Kavita":65, "Amit":51, "Julie":68, "Kavita":66, "Amar":48} marks Out[5]: {'Laxman': 56, 'Kavita': 66, 'Amit': 51, 'Julie': 68, 'Amar': 48}To access value:To obtain value associated with certain key use get() method. It can also be fetched by using [] operator.In [6]: capitals={"Maharashtra":"Mumbai", "Telangana":"Hyderabad", "Tamilnadu":"Chennai", "Karnataka":"Bengaluru", "Bihar":"Patna"} capitals.get("Karnataka") Out[6]: 'Bengaluru' In [7]: prices={"pen":25, "bike":50000, "mobile": 5000,"book": 250 } prices['bike'] Out[7]: 50000To update value:To update the dictionary, just assign a new value to existing key. If the key is not currently used, a new key-value pair is added to dictionary.In [8]: ChiefMinisters={"Maharashtra":"Fadanvis","UP":"Yogi", "Karnataka":"KumarSwamy", "MP":"chauhan"} ChiefMinisters["MP"]="KamalNath" ChiefMinisters["Maharashtra"]="Thakre" ChiefMinisters Out[8]: {'Maharashtra': 'Thakre', 'UP': 'Yogi', 'Karnataka': 'KumarSwamy', 'MP': 'KamalNath'} In [9]: ChiefMinisters["Delhi"]="Kejriwal" ChiefMinisters Out[9]: {'Maharashtra': 'Thakre', 'UP': 'Yogi', 'Karnataka': 'KumarSwamy', 'MP': 'KamalNath', 'Delhi': 'Kejriwal'}Dictionary Built-in functionslen()returns number of key: value pairs in dictionarymax()If all keys in dictionary are numbers, largest number will be returned. If all keys in dictionary are strings, one that comes last in alphabetical order will be returned.min()If all keys in dictionary are numbers, smallest number will be returned. If all keys in dictionary are strings, one that comes first in alphabetical order will be returned.In [10]: players={"A":"Anderson", "B":"Bravo", "C":"Currran","D":"Dhawan"} len(players) Out[10]: 4 In [11]: print ('max :',max(players)) print ('min : ', min(players))        max : D min :  A In [12]: digwords={2:"two",9:"nine", 6:"six", 1:"one"} print ('max:', max(digwords)) print ('min:', min(digwords)) max: 9 min: 1Dictionary class methodsdict()creates a new dictionary objectclear()Remove all items from dictionary.  copy()a shallow copy of dictionaryfromkeys()Returns a new dict with keys from iterable and values equal to value.  get()returns value associated with key  items()list of tuples – each tuple is key value pair  keys()list of dictionary keys  pop()remove specified key and return the corresponding value.popitem()remove and return some (key, value) pair as a 2-tuple.setdefault()dictionary.get(k,dictionary), also set DICTIONARY[k]=dictionary if k not in dictionaryupdate()Update dictionary from another dict/iterablevalues()list of dictionary valuesdict() is a built-in function. If used without parameter, it creates an empty dictionary. The function uses a list of two item tuples as parameter.The new dictionary object is constructed with each tuple treated as key-value pair.In [13]: d1=dict() d1 Out[13]: {} In [14]: dict([(1,100),(2,200),(3,300)]) Out[14]: {1: 100, 2: 200, 3: 300} In [15]: dict(a=1, b=2, c=3) Out[15]: {'a': 1, 'b': 2, 'c': 3}items(), keys() and values() methods return view objects that are lists of k:v pairs, keys and values respectively. Any change in composition of dictionary will automatically reflect in these view objects.In [16]: CMs={'Maharashtra': 'Thakre', 'UP': 'Yogi', 'Karnataka': 'KumarSwamy', 'MP': 'KamalNath', 'Delhi': 'Kejriwal'} CMs.items() Out[16]: dict_items([('Maharashtra', 'Thakre'), ('UP', 'Yogi'), ('Karnataka', 'KumarSwamy'), ('MP', 'KamalNath'), ('Delhi', 'Kejriwal')]) In [17]: CMs.keys() Out[17]: dict_keys(['Maharashtra', 'UP', 'Karnataka', 'MP', 'Delhi']) In [18]: CMs.values() Out[18]: dict_values(['Thakre', 'Yogi', 'KumarSwamy', 'KamalNath', 'Kejriwal']) In [19]: CMs.pop("UP") Out[19]: 'Yogi'update() method merges two dictionaries by updating values with common keys in both and adding items with new keys from another dictionary.In [20]: CMs Out[20]: {'Maharashtra': 'Thakre', 'Karnataka': 'KumarSwamy', 'MP': 'KamalNath', 'Delhi': 'Kejriwal'} In [21]: d2={"Punjab":"Amrindersingh","Bengal":"Mamata", "Odisha":"Patnaik"} CMs.update(d2) In [22]: CMs Out[22]: {'Maharashtra': 'Thakre', 'Karnataka': 'KumarSwamy', 'MP': 'KamalNath', 'Delhi': 'Kejriwal', 'Punjab': 'Amrindersingh', 'Bengal': 'Mamata', 'Odisha': 'Patnaik'}clear() method removes all items from dictionary, though the object remains in the memory. The del keyword in Python removes the object from memory altogether.In [23]: CMs.clear() CMs Out[23]: {} In [24]: del CMs CMs --------------------------------------------------------------------------- NameError                                Traceback (most recent call last) <ipython-input-24-66687de12b16> in <module>()       1 del CMs ----> 2 CMs NameError: name 'CMs' is not defined
Rated 5/5 based on 11 customer reviews
logo

Python Tutorial

Python’s dictionary is also a collection type object. However, unlike list or tuple, it is not a sequence. It is a mapping type object. Dictionary is an unordered collection of comma separated key-value pairs. Key is mapped to its value by special hashing mechanism of Python interpreter. Association of key to value is marked by : symbol between them.

Some examples of dictionary objects are shown below:

In [1]:
capitals={"Maharashtra":"Mumbai", "Telangana":"Hyderabad", "Tamilnadu":"Chennai", "Karnataka":"Bengaluru", "Bihar":"Patna"}
rankings={1:"India", 2:"England", 3:"South Africa", 4:"Australia", 5:"New Zealand"}
prices={"pen":25, "bike":50000, "mobile": 5000,"book": 250 }
In [2]:
print ("state capitals:", capitals)
print ("Team rankings:", rankings)
print ("prices:",prices)
Out[2]:
state capitals: {'Maharashtra': 'Mumbai', 'Telangana': 'Hyderabad', 'Tamilnadu': 'Chennai', 'Karnataka': 'Bengaluru', 'Bihar': 'Patna'}
Team rankings: {1: 'India', 2: 'England', 3: 'South Africa', 4: 'Australia', 5: 'New Zealand'}
prices: {'pen': 25, 'bike': 50000, 'mobile': 5000, 'book': 250}

Key should be an immutable object. Number, string or tuple can be used as key in dictionary. Use of mutable object as key will raise TypeError. Any object is valid for use as value.

In [3]:
manufacturers={("Nokia", "Samsung","MicroMax"):"Mobiles", ("Nike", "Adidas", "Puma"):"Sports Goods",
              ("Honda","Bajaj", "TVS"):"Bikes"}
sports={"indoors":["chess", "Badminton", "Table Tennis"], "outdoor":["Cricket", "Football", "Rugby"]}
In [4]:
animals={["snake", "Lizard"]:"reptiles", ["Parrot", "Crow"]:"birds"}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-1904d3d80b08> in <module>()
----> 1 animals={["snake", "Lizard"]:"reptiles", ["Parrot", "Crow"]:"birds"}

TypeError: unhashable type: 'list'

Same Key doesn’t appear more than once in one collection. One value can be assigned to more than one keys. If key is used more than once, only the last will be retained.

In [5]:
marks={"Laxman":56, "Kavita":65, "Amit":51, "Julie":68, "Kavita":66, "Amar":48}
marks
Out[5]:
{'Laxman': 56, 'Kavita': 66, 'Amit': 51, 'Julie': 68, 'Amar': 48}

To access value:

To obtain value associated with certain key use get() method. It can also be fetched by using [] operator.

In [6]:
capitals={"Maharashtra":"Mumbai", "Telangana":"Hyderabad", "Tamilnadu":"Chennai", "Karnataka":"Bengaluru", "Bihar":"Patna"}
capitals.get("Karnataka")
Out[6]:
'Bengaluru'
In [7]:
prices={"pen":25, "bike":50000, "mobile": 5000,"book": 250 }
prices['bike']
Out[7]:
50000

To update value:

To update the dictionary, just assign a new value to existing key. If the key is not currently used, a new key-value pair is added to dictionary.

In [8]:
ChiefMinisters={"Maharashtra":"Fadanvis","UP":"Yogi", "Karnataka":"KumarSwamy", "MP":"chauhan"}
ChiefMinisters["MP"]="KamalNath"
ChiefMinisters["Maharashtra"]="Thakre"
ChiefMinisters
Out[8]:
{'Maharashtra': 'Thakre',
'UP': 'Yogi',
'Karnataka': 'KumarSwamy',
'MP': 'KamalNath'}
In [9]:
ChiefMinisters["Delhi"]="Kejriwal"
ChiefMinisters
Out[9]:
{'Maharashtra': 'Thakre',
'UP': 'Yogi',
'Karnataka': 'KumarSwamy',
'MP': 'KamalNath',
'Delhi': 'Kejriwal'}

Dictionary Built-in functions

len()returns number of key: value pairs in dictionary
max()If all keys in dictionary are numbers, largest number will be returned. If all keys in dictionary are strings, one that comes last in alphabetical order will be returned.
min()If all keys in dictionary are numbers, smallest number will be returned. If all keys in dictionary are strings, one that comes first in alphabetical order will be returned.
In [10]:
players={"A":"Anderson", "B":"Bravo", "C":"Currran","D":"Dhawan"}
len(players)
Out[10]:
4
In [11]:
print ('max :',max(players))
print ('min : ', min(players))       
max : D
min :  A
In [12]:
digwords={2:"two",9:"nine", 6:"six", 1:"one"}
print ('max:', max(digwords))
print ('min:', min(digwords))
max: 9
min: 1

Dictionary class methods

dict()creates a new dictionary object
clear()Remove all items from dictionary.  
copy()a shallow copy of dictionary
fromkeys()Returns a new dict with keys from iterable and values equal to value.  
get()returns value associated with key  
items()list of tuples – each tuple is key value pair  
keys()list of dictionary keys  
pop()remove specified key and return the corresponding value.
popitem()remove and return some (key, value) pair as a 2-tuple.
setdefault()dictionary.get(k,dictionary), also set DICTIONARY[k]=dictionary if k not in dictionary
update()Update dictionary from another dict/iterable
values()list of dictionary values

dict() is a built-in function. If used without parameter, it creates an empty dictionary. The function uses a list of two item tuples as parameter.The new dictionary object is constructed with each tuple treated as key-value pair.

In [13]:
d1=dict()
d1
Out[13]:
{}
In [14]:
dict([(1,100),(2,200),(3,300)])
Out[14]:
{1: 100, 2: 200, 3: 300}
In [15]:
dict(a=1, b=2, c=3)
Out[15]:
{'a': 1, 'b': 2, 'c': 3}

items(), keys() and values() methods return view objects that are lists of k:v pairs, keys and values respectively. Any change in composition of dictionary will automatically reflect in these view objects.

In [16]:
CMs={'Maharashtra': 'Thakre', 'UP': 'Yogi', 'Karnataka': 'KumarSwamy', 'MP': 'KamalNath', 'Delhi': 'Kejriwal'}
CMs.items()
Out[16]:
dict_items([('Maharashtra', 'Thakre'), ('UP', 'Yogi'), ('Karnataka', 'KumarSwamy'), ('MP', 'KamalNath'), ('Delhi', 'Kejriwal')])
In [17]:
CMs.keys()
Out[17]:
dict_keys(['Maharashtra', 'UP', 'Karnataka', 'MP', 'Delhi'])
In [18]:
CMs.values()
Out[18]:
dict_values(['Thakre', 'Yogi', 'KumarSwamy', 'KamalNath', 'Kejriwal'])
In [19]:
CMs.pop("UP")
Out[19]:
'Yogi'

update() method merges two dictionaries by updating values with common keys in both and adding items with new keys from another dictionary.

In [20]:
CMs
Out[20]:
{'Maharashtra': 'Thakre',
'Karnataka': 'KumarSwamy',
'MP': 'KamalNath',
'Delhi': 'Kejriwal'}
In [21]:
d2={"Punjab":"Amrindersingh","Bengal":"Mamata", "Odisha":"Patnaik"}
CMs.update(d2)
In [22]:
CMs
Out[22]:
{'Maharashtra': 'Thakre',
'Karnataka': 'KumarSwamy',
'MP': 'KamalNath',
'Delhi': 'Kejriwal',
'Punjab': 'Amrindersingh',
'Bengal': 'Mamata',
'Odisha': 'Patnaik'}

clear() method removes all items from dictionary, though the object remains in the memory. The del keyword in Python removes the object from memory altogether.

In [23]:
CMs.clear()
CMs
Out[23]:
{}
In [24]:
del CMs
CMs
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-24-66687de12b16> in <module>()
      1 del CMs
----> 2 CMs

NameError: name 'CMs' is not defined

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

C# Tutorial

By KnowledgeHut

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
Rated 5/5 based on 12 customer reviews
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More