Dictionaries

Dictionaries

What is Dictionary?
                   A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values.
                Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

                Ok, so there is more to life than the names of your cats. You need to call your sister, mother, son, the fruit man, and anyone else who needs to know that their favourite cat is dead. For that you need a telephone book.
                Now, the lists we've used above aren't really suitable for a telephone book. You need to know a number based on someone's name - not the other way around, like what we did with the cats. In the examples of months and cats, we gave the computer a number, and it gave us a name. This time we want to give the computer a name, and it give us a number. For this we need dictionaries.
                So how do we make a dictionary? Put away your binding equipment, it isn't that advanced.
Remember, dictionaries have keys, and values. In a phone book, you have people's names, then their numbers. See a similarity?
                When you initially create a dictionary, it is very much like making a tuple or list. Tuples have ( and ) things, lists have [ and ] things. Guess what! dictionaries have { and } things - curly braces. Here is an example below, showing a dictionary with four phone numbers in it:

Code Example 7 - Creating a dictionary

#Make the phone book:
phonebook = {'Andrew Parson':8806336, \
'Emily Everett':6784346, 'Peter Power':7658344, \
'Lewis Lame':1122345}
                The program would then print Lewis Lame's number onscreen. Notice how instead of identifying the value by a number, like in the cats and months examples, we identify the value, using another value - in this case the person's name.
                Ok, you've created a new phone book. Now you want to add new numbers to the book. What do you do? A very simple line of code:

Code Example 8 - Adding entries to a dictionary

#Add the person 'Gingerbread Man' to the phonebook:

phonebook['Gingerbread Man'] = 1234567

# Didn't think I would give you
# my real number now, would I?
All that line is saying is that there is a person called Gingerbread Man in the phone book, and his number is 1234567. In other words - the key is 'Gingerbread Man', and the value is 1234567.
You delete entries in a dictionary just like in a list. Let's say Andrew Parson is your neighbour, and shot your cat. You never want to talk to him again, and therefore don't need his number. Just like in a list, you'd do this:

Code Example 9 - Removing entries from a dictionary
del phonebook['Andrew Parson']

                Again, very easy. the 'del' operator deletes any function, variable, or entry in a list or dictionary (An entry in a dictionary is just a variable with a number or text string as a name. This comes in handy later on.)
                Remember that append function that we used with the list? Well, there are quite a few of those that can be used with dictionaries. Below, I will write you a program, and it will incorporate some of those functions in. It will have comments along the way explaining what it does.
                Type this program into Python IDLE (you can skip the comments). Experiment as much as you like with it. Type it where you see the lines beginning with >>>

Code Example 10 - Functions of dictionaries
#A few examples of a dictionary

#First we define the dictionary
#it will have nothing in it this time
ages = {}

#Add a couple of names to the dictionary
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45

#Use the function has_key() -
#This function takes this form:
#function_name.has_key(key-name)
#It returns TRUE
#if the dictionary has key-name in it
#but returns FALSE if it doesn't.
#Remember - this is how 'if' statements work -
#they run if something is true
#and they don't when something is false.
if ages.has_key('Sue'):
    print "Sue is in the dictionary. She is", \
ages['Sue'], "years old"

else:
    print "Sue is not in the dictionary"

#Use the function keys() -
#This function returns a list
#of all the names of the keys.
#E.g.
print "The following people are in the dictionary:"
print ages.keys()

#You could use this function to
#put all the key names in a list:
keys = ages.keys()

#You can also get a list
#of all the values in a dictionary.
#You use the values() function:
print "People are aged the following:", \
ages.values()

#Put it in a list:
values = ages.values()

#You can sort lists, with the sort() function
#It will sort all values in a list
#alphabetically, numerically, etc...
#You can't sort dictionaries -
#they are in no particular order
print keys
keys.sort()
print keys

print values
values.sort()
print values

#You can find the number of entries
#with the len() function:
print "The dictionary has", \


len(ages), "entries in it"


Built-in Dictionary Functions & Methods:

Python includes following dictionary functions
SN
Function with Description
1
cmp(dict1, dict2)
Compares elements of both dict.
2
len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3
str(dict)
Produces a printable string representation of a dictionary
4
type(variable)
Returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

Python includes following dictionary methods:

SN
Methods with Description
1
dict.clear()
Removes all elements of dictionary dict
2
dict.copy()
Returns a shallow copy of dictionary dict
3
dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4
dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5
dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6
dict.items()
Returns a list of dict's (key, value) tuple pairs
7
dict.keys()
Returns list of dictionary dict's keys
8
dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9
dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10
dict.values()
Returns list of dictionary dict's values



No comments: