COSC 1336 | PyThon

ACC

Data Types

Foreword

In this course, we cover the most commonly used Python data types as outlined in the Python Language Reference.

The following four general data types are discussed in the course and, unless otherwise stated, will be used in examples:

  • Numbers (Integer, Boolean, Real, Complex)
  • Sequences (Immutable - String, Tuple, Bytes; Mutable - Lists, Byte Arrays)
  • Mappings (Dictionary)
  • Sets

Tuples are created with parentheses () (and no parenthesess; the default), lists are created with square brackets [], dictionaries and sets are both created with braces {}. Dictionaries are covered below.

Data Types - Mappings

Mappings - the dictionary is currently the only mapping data type in Python.

These are facts about and attributes of Python dictionaries:

  • Is a mapping and not a sequence
  • Are mutable
  • Are unordered (however, the built-in collections module contains an ordered dictionary)
  • Note: as of Python 3.7, dictionaries are ordered
  • Do not support the sequence operations listed in the "Data Types Sequences" chapter
  • Do support the mapping operations listed in the table below
  • Keys must be immutable objects
  • Use empty braces '{}' to create an empty dictionary
  • Consist of key:value pairs
  • Duplicate keys are not allowed
  • Duplicate values are allowed

A dictionary in computer science has multiple names depending on the language:

  • Associative array - PHP
  • Dictionary - Python, Smalltalk, Objective-C, .NET, Swift
  • Hash - Ruby
  • Hash table - Lisp
  • JSON Object - JavaScript
  • Map - C++, Haskell, Java (implemented as Hashmap)
  • Symbol table - Lua

You may be interested in this video explaining Python Dictionaries.

The table below lists common operations that are used with mappings.

Operations in Mappings (Dictionaries)
d = {} creates an empty dictionary
d = {'k':'v'} creates a dictionary with keys and values
values() returns a sequence of tuples
pop('key') returns the value AND removes the item (or default)
get() returns the value (or default)
del deletes the item; use if 'in' before deleting
clear() removes all items
d1['key'] = 'value' adds a new element to dictionary d1
items() returns all keys AND values
keys() returns all keys
popitem() returns arbitrary value AND removes that item
in returns True if key in the dictionary
not in returns True if key NOT in the dictionary
d1.update(d2) adds items in d2 to d1

 

Code dictionary.py in PyCharm as shown. The comments in the code and annotations in the output describe the operations being demonstrated. All of the operations in the table above are shown in the code example below. Confirm your understanding by closely comparing the code with the output it produces.

Here's the output.

More dictionary examples:

dictionary-examples.py.png

Here's the output:

dictionary-examples-output.png