Tuesday, March 20, 2012

Dictionary

In this post we will discuss, one more method known as Dictionary.

* What is a Dictionary?

Well, it is pretty much like Lists and Tuples as we discussed earlier, but the structure of Dictionary makes itself different from other. Its a collection or group of any data type value. Dictionary has a 'key' and a 'key-value'

* How to Identify a Dictionary?

By its structure ie by its syntax, and of course we have the built-in keyword type() to reveal what it is. Elements of Dictionary are enclosed within curly brackets.

Syntax: variable_name = {key1:value1, key2:value2, . . . . . keyn:valuen}

Lets Open up the Python Shell and check with an example.

>>> subject = {1:'Science', 2:'Maths', 3:'Computer', 4:'Literature'}
>>> subject
{1: 'Science', 2: 'Maths', 3: 'Computer', 4: 'Literature'}
>>> type(subject)
<type 'dict'>
>>>
>>> #  To call any key_value we need to call by its key, Syntax: dictionary_name[key]
>>> subject[1]
'Science'
>>> subject[4]
'Literature'
>>> len(subject)
4
>>> subject.pop(2)
'Maths'
>>> # pop removes the value of the key_value given and displays what has been removed
>>> subject
{1: 'Science', 3: 'Computer', 4: 'Literature'}
>>> ages={'bob': 20, 'nancy': 18, 'sam': 24}
>>> # We have created another Dictionary named ages for the next examples here
>>> subject=ages.copy()
>>> # Copies elements from one dictionary and pastes it to another dictionary
>>> subject
{'bob': 20, 'sam': 24, 'nancy': 18}
>>> ages.clear()
>>> # clears all the elements from a dictionary.
>>> ages
{}
>>> subject.items()
[('bob', 20), ('sam', 24), ('nancy', 18)]
>>>  # Displays list of Subjects (key, value) pairs, as tuples
>>> subject.keys()
['bob', 'sam', 'nancy']
>>> subject.values()
[20, 24, 18]
>>> subject[5]='Python'
>>> # As of now just know that this adds an element to the dictionary
>>> subject
{'bob': 20, 'sam': 24, 'nancy': 18, 5: 'Python'}
>>>>>> subject.has_key(0)
False
>>> subject.has_key(5)
True
>>> # dictionary_name.has_key(key_value) returns true or false; True if the key value is present, and False if its not present


These are the basic things that you are supposed to know as of now, we will see more usage of Lists, Tuples and Dictionaries gradually in our Future Posts.

So, I Hope This was Informative for you, Practice it, and Don't Forget to check on my next post.

Thank You.

0 comments:

Post a Comment