banner

© 2004-19 ict4u.net

Python Data Structures - Dictionaries

Python has a rich and varied collection of data structures the simplest is the List

Dictionaries can be contained in lists and vice versa. So what's the difference between lists and dictionaries?
Lists are ordered sets of objects, whereas dictionaries are unordered sets. The main difference is that items in dictionaries are accessed via keys and not via their position.
A dictionary is an associative array. Each key of the dictionary is associated (or mapped) to a value.
The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.

Create a dictionary and assign values to it like this:

# Countries and the continent where they are situated
dictCountries = {"Burundi":"Africa","Algeria":"Africa","Eygpt":"Africa","Cambodia":"Asia","Denmark":"Europe"}
					

Here is a complete list of the methods that can be used on lists:

Operation Description
len(dataDict) returns the number of entries, i.e. the number of (key,value) pairs.
del dataDict(k) deletes the key k together with its value
dataDict.clear() Removes all elements of dictionary dict
dataDict.copy() Returns a shallow copy (click here for a description of shallow/deep copy) of dictionary dict
dataDict['a']=1
dataDict.update({'a':1})
Adds or updates the key a with the value 1.
Both methods are equivalent. If the key does not exist it is added
dataDict.fromkeys() Create a new dictionary with keys from seq and values set to value.
dataDict.get(key, default=None) For key key, returns value or default (None) if key not in dictionary Note For the second parameter, enter a string otherwise None will be returned
dataDict.items() Returns a list of dict's (key, value) tuple pairs
dataDict.values() Returns list of dictionary dict's values
dataDict.keys() Returns list of dictionary dict's keys
dataDict.update(dataDict2) Adds dictionary dict2's key-values pairs to dict

The methods in the table below will help you understand how to use them in your code

Method Description
Add or Update dictionary key/value Add/update a dictionary
Delete dictionary key/value Delete a key/value pair from a dictionary
Dictionary From List Create a dictionary from two lists
Display Dictionary Data Display key value pairs from a dictionary
Get data element using a key Get data from a dictionary using a key value
Initialise dictionary and count Setup a dictionay and count the number of entries
Sort Dictionary Data Sort a dictionary by key or by value