Chapter 11: Dictionaries (Notes from Think Python)

Dictionary

Dictionary

 Dictionaries :

It is best to think of a dictionary as an unordered set of  key: value  pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

Source: Python Software Foundation / 5.5 Dictionaries

  • Elements of a dictionary are never indexed.
  • Indices are called “keys”
  • A ” KeyValue ” pair is an Item
  • To add items (Key-Value pairs), we can use [ ] :

>>> eng2span [‘one’] = [‘uno’]
>>> print eng2span
{ ‘one’ : ‘uno’ }   key     value

>>> eng2span = {‘one’:’uno’ , ‘two’:’dos’ , ‘three’:’tres’}

Python uses Keys to look up the corresponding values.

>>> print eng2span [‘two’]
‘dos’

Operators :

  • in : It tells you whether something appears as a Key in the dictionary.
    >>> ‘one’ in eng2span
    True
  • NOTE 1 : Python uses an algorithm called a hashtable for the in operator.
  • NOTE 2 : Hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use integers, called Hash Values, to store and look up Key-Value pairs.
  • TIP : Use Hash with immutable keys.

Built-in functions :

  • len ( ) : works on dictionaries
    >>> len (eng2span)
    3
  • dict ( ) : creates a new dictionary with no items { }

Methods :

  • values ( ) :
    >>> vals = eng2span.values()
    >>> ‘uno’ in vals    #Recall that ‘uno’ is a Value
    True
  • items ( ) : This method returns a list of tuples, where each tuple is a key-value pair.
    >>> d = { ‘a’: 0, ‘b’:1, ‘c’:2}
    >>> t = d.items()
    >>> print t
    [  (‘a’, 0),       (‘b’,1),           (‘c’,2) ]    # List of Tuples
    tuple           tuple             tuple
    key-value     key-value       key-value   #Each pair of key-value is an item.NOTE : The items of the dictionary are in no particular order.

Memo :

In order to keep track of values that have already been computed, we can store them in a dictionary.

[…] A previously computed value that is stored for later use is called a memo.

Source: Think Python by Allen B. Downey

Global Variables :

Variables in _ _main_ _ are sometimes called global because they can be accessed from any function. Unlike local variables, which disappear when their function ends, global variables persist from one function call to the next from any function. They persist from one function call to the next.
Source: Think Python by Allen B. Downey

  • Common use: Use Global Variables for flags, that is, Boolean variables that indicate (“flag”) whether a condition is true.
  • To reassign a Global Variable we have to declare the Global Variable before we use it:
    – been_called = False
    – def example2 ( ):
    – TAB global been_called
    – TAB been_called = TrueNOTE: If the Global Variable is mutable, we can modify it without declaring it.

Dictionaries as a set of counters :

Implentation no1 :
  • Create 26 variables one of each letter of the alphabet.
    – Traverse strings, and chained conditional to increment the corresponding counter.
Implentation no2 :
  • List with 26 elements.
    – Convert each character into a number, using the built-in function ord ( ).
    – Use the number as an index into the list, and increment the appropriate counter.
Implementation no3:
  • Create a dictionary with { character : counters }
    keys            values
  • We could add new items to the dictionary.
  • We could also increment the value of an existing item.

Looping and Dictionaries

  • The for statement traverses the keys of the dictionary.
    – def print_hist (h):   # where variable ‘h’ is a dictionary
    – TAB for c in h :
    – TAB TAB print  c,  h[c]
    key  value

Statements :

  • for

Lookups :

  • Given dictionary ‘d’
  • Given a Key ‘k’
  • Given the corresponding value of k, v   #where variable ‘v’ is a value
  • Forward Lookup : v = d [ k ]
  • No simple syntax to do a Reverse Lookup.

Long integers

>>> fibonacci (50)
12586269025L     #where L stands for Long Integer

Mathematical operators work with long integers, and the functions in the math module, too, so in general any code that works with int will also work with long.

Source: Think Python by Allen B. Downey

Tips for Debugging bigger datasets :

  •  Scale down input
    – Edit the files themselves
    or
    – Modify the program to read only the first n lines
  • Check summaries and types
    – Print summaries of the data: Number of items in a dictionary ; Total of a list of numbers
    – A common cause in runtime errors is a value that is not the right type. TO DEBUG: Print the type of a value
  • Write self-checks
    – Write code to check errors automatically
  • Pretty print the output
    – Formatting debugging output

To finish here is an image to visualize Strings, Lists and Dictionaries.

String / List / Dictionary in Python

String / List / Dictionary in Python

 

Olé to you nonetheless just for having the sheer human love and stubbornness to keep showing up.

Elizabeth Gilbert – TED Talk

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s