Introduction:-


Hi guyz today I am going to writing a tutorial on dictionaries in Python....As per as getting comments from my readers I'll try to make this tutorial Short....

Layout:-

1.What are dictionaries?
2.Why dictionaries?
3.How to declare/make dictionaries in Python?
4.What all you can do with a dictionary?
5.Interesting Functions?
6.Dictionary Methods?


What are dictionaries?

Dictionaries are simply another type of Sequence in Python..
Like in English dictionaries you search for a word and its meaning … Same happens in python...
Dictionaries in Python have a “key” and a “value of that key”... That may seem strange for the first time but I promise I'll make it easy in the next few topics...

Why Dictionaries?

A common question which comes into ones mind is that why we dictionaries in python..
The answer is pretty simply “When indexing and slicing doesn't do” ….If you are not familiar with that I suggest you to read my previous tutorials on this topic...

Now , That we have a simple picture of these dictionaries ...Let's know how to use them...

How to ? Dictionaries in Python?

Declaring dictionaries in python is pretty ****! Simple... I found them easier than any of other sequences I have learn t about..

To declare a dictionary in python We enclose them in curly brasses [ “{“ and “}” ] And rest I'll explain after showing you this piece of code....

dic = { "Aneesh" : 15, "Sonal" : 40 } 
print dic

Output:-

{'Aneesh': 15, 'Sonal': 40}


Yupi , we just declared a dictionary....That wasn't difficult...Was that...

Explanation:-

As I told you above that a Dictionaries in Python have a “key” and a “value of that key” Here above we declared 2 keys and two values...

1.Aneesh with a value of 15
2.Sonal with a value of 40

In python we separate a key and its value by a colon [“:”]...

That's pretty simple....

What you can do ? With a dictionary?

To demonstrate what we can do with a simple dictionary...Lets build a interesting code...

dic = { "Aneesh" : "Programmer" , "Sonal" : "Teacher" , "Sachin" : "Buisnessman" }

print dic["Aneesh"] # It'll print out this keys value...In this case 				Programmer.... Basic syntax :- d[k]

dic["Aneesh"] = "Writter" # Assigns the value "Writter to the key "Aneesh" 					in the dictionary "dict" .....Basic 					syntax:- dictionary[key] = value


String Formatting with Dictionaries:-

For this you should know what is string formatting in Python …

dic = { "Aneesh" : "Programmer" , "Sonal" : "Teacher" , "Sachin" : "Buisnessman" } 

print "Hey do you know Aneesh is a %(Aneesh)s and Sonal is a %(Sonal)s " % dic

Output:-

Hey do you know Aneesh is a Programmer and Sonal is a Teacher


explanation:-

Pay close attention to the last line of the Code... … when we write “%(Aneesh)s” % dic the code says to that Search for this key in this dictionary and print it out to me....We use a 's' at the end because we want Python to know that its a String...

INTERESTING FUNCTIONS:-

The dict function:-

We can use this dict function to construct a dictionary from other mappings eg:- other dictionaries or from sequences of key,value pairs...

tup = ( ('key','value') , ('key2','value') ) 
dic = dict(tup)  
print dic

Above I declared a tuple “tup” of 2 tuples …This may seem confusing at first but you'll have a better understanding of these as you grow more as a programmer...

Output:-

{'key2': 'value', 'key': 'value'}

dict returns an empty dictionary when used with no arguments...

The len function:-

This function simply returns no of items(key,value pairs) in a dictionary..

dic = { "Aneesh" : "Programmer" , "Sonal" : "Teacher" , "Sachin" : "Buisnessman" } 
print len(dic)

Output :-

3

Dictionary Methods:-

Just like any other sequence in python dictionaries to have their methods...Let's learn about them:-

clear

clear simply removes all items from a dictionary … and returns Nothing ...or None...
It takes no arguments...

dic = { "Aneesh" : "Programmer" , "Sonal" : "Teacher" , "Sachin" : "Buisnessman" } 

dic.clear() 
print dic

output:-

{}

copy:-

What copy does is that it returns a new dictionary with the same items[key,values]

dic = { "Aneesh" : "Programmer" , "Sonal" : "Teacher" , "Sachin" : ["Businessman","Social Worker"] } 

dic2 = dic.copy() 

dic2["Aneesh"] = "Writter" 
dic2["Sachin"].remove("Businessman") 
print dic 
print dic2

Output:-

{'Aneesh': 'Programmer', 'Sachin': , 'Sonal': 'Teacher'}
{'Aneesh': 'Writter', 'Sonal': 'Teacher', 'Sachin': }

Explanation:-

In The above code I just declared a dictionary “dic” with 3 keys and 3 values … Have a look at the third value its a list...
So , key “Sachin” now have 2 values “Businessman” and “Social Worker”...

then I made a copy of dic and saved it in dic2.
I changed the dic2[“Aneesh”] value to “Writer” ...And I removed one value[“Businessman”] of dic2["Sachin"]...Then what do we observer in output...
In both the dic's the “Businessman” is missing...

This you have to keep in mind while using copy function...

To avoid this problem is function called deepcopy which is present in module “copy”

from copy import deepcopy 
dic = { "Aneesh" : "Programmer" , "Sonal" : "Teacher" , "Sachin" : ["Buisnessman","Social Worker"] } 

dic2 = deepcopy(dic)# basic syntax :- d1 = deepcopy(dictionary) 

dic2["Aneesh"] = "Writter" 
dic2["Sachin"].remove("Buisnessman") 
print dic 
print dic2

OUTPUT:-

{'Aneesh': 'Programmer', 'Sachin': , 'Sonal': 'Teacher'}
{'Aneesh': 'Writter', 'Sonal': 'Teacher', 'Sachin': }


Fromkeys:-

The fromkey method returns a new dictionary with the given keys...

dic = {}

print (dic.fromkeys(["Name","Age"]))

print (dic)

Output:-

{'Age': None, 'Name': None}

{}


This method doesn't builds a dictionary it simply returns one...As you can see in the output the dictionary “dic” still remains unchanged....

This method inputs a list of keys and a value to assign to them ...If not given any value they assign a None by default....

simple :-


Now a code demonstrating the input of value:-

dic = {}

print (dic.fromkeys(["Name","Age"],"Test"))

print (dic)

Output:-

{'Age': 'Test', 'Name': 'Test'}

{}


Get:-

Before getting to this function suppose that you are making a Professional phone-book program for a Big company...And now if your client just searched for a name in the phone-book..You don't want them to see those nasty errors
eg:-

dic = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}



#Suppose a client enters a name Sachin to search for



print dic["Sachin"]

Output:-

Traceback (most recent call last):

File "dic.py", line 5, in <module>

print dic["Sachin"]

KeyError: 'Sachin'


Hey you don't want that...


For avoiding this Python have a get method...

The get method:-

Now lets rewrite out previous code with the get method...

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}



#Suppose a client enters a name Sachin to search for



print d.get("Sachin")

Output:-

None

Hey now it looks pretty neat...
One more thong you can do with this method is that you can also provide it a value other than None to show it on screen …

eg:-

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}



#Suppose a client enters a name Sachin to search for



print d.get("Sachin","Not found")

Output:-

Not found


Hey now that's what I call a professional code...

has_key:-

This method checks whether the given key is present in a dictionary or not..It returns True if it finds it or false if its not found...

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}



print d.has_key("Aneesh")

print d.has_key("Sachin")

Output:-

True

False


Simple...

items:-

Pretty simple method ...And I have been talking about them all day long while writing this tutorial...

It simply returns all items of the dictionary as a list in (key,value) format...

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}





print d.items()


Output:-

[('Aneesh', '0000000000'), ('Sonal', '1111111111')]


Simple enough.. no need to explain
Same as items there's another method keys which returns the list of keys in the dictionary...
Pretty simple......

There's another method iteritems() and iterkeys().. which simply converts a dictionary into an iterator... I don't wanna talk about them in this beginners tutorials...


POP:-


This is another one of the simplest methods in python...It simply inputs a key as an argument and removes the key , value associated with that key... It returns the value associated with the key inputed..

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}



print d.pop("Aneesh")

print d

Output:-

0000000000

{'Sonal': '1111111111'}


popitem:-

method popitem() is somewhat similar to method list.pop() which pop's out the last element in the list....But popitem() simply removes the first item of the dictionary as there is no last item in a dictionary...

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}



print d.popitem()

print d

Output:-

('Aneesh', '0000000000')

{'Sonal': '1111111111'}


setdefault:-

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}



print d.setdefault("Sachin","unknown")

print d

Output:-

unknown

{'Aneesh': '0000000000', 'Sachin': 'unknown', 'Sonal': '1111111111'}


explanation:-

This method is quite similar to get method explained above ...But what makes it different is that unlike gets it simply sets the default value to the key if not found …

In the above case the program searches for “Sachin” in the dictionary...It doesn't find it. So Python tells the program to make a new key “Sachin” and set it to default value...In this case “unknown”

Update:-

Imagine if you changed your phone and you want to update your new phone's Phonebook with your old phone's ..And also avoid repetition.. What would you do...
There update method comes into use:-

d = {"Aneesh" : "0000000000" , "Sonal" : "1111111111"}

d2 = {"Sachin" : "77878884884" , "Aneesh" : "099990099" , "Sonal" : "1111111111","Kamla" : "9999999999" }

d.update(d2)

print d


Output:-

{'Aneesh': '099990099', 'Kamla': '9999999999', 'Sonal': '1111111111', 'Sachin': '77878884884'}

This program is easy enough …......So figure it out yourself...


Values:-

Values method simply return a list of values in the dictionary … But unlike keys the values can be repetitive...

d = {"Aneesh" : "0000000000" , "Sonal" : "0000000000"}

print d.values()

Output:-


There's also another method itervalues() which returns an iterator of values...


That's all about dictionaries …..
Thanks for reading...
Fell free to add comments...........

jcao219 commented: Good for beginners. +1
JoshuaBurleson commented: Please post tutorials in the correct section, also no chat or leet speech per daniweb rules, and please use only English in code for tutorials -1

Recommended Answers

All 2 Replies

Very nice tutorial. Thank You.

commented: Does not conttobute, use upvote/reputation for appresiation -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.