Python Data Types and Structures: Tuples, Dictionaries, and Containers

This Python programming tutorial covers data types, data structures, tuples, dictionaries, containers, and related concepts.

Working with Data

  • Most programs involve working with data.
  • This section explores how Python programmers represent and manipulate data.
  • We’ll also cover common programming idioms used in Python.

Primitive Datatypes

Python offers a few fundamental data types:

  • Integers: Whole numbers (e.g., 10, -5, 0).
  • Floating-point numbers: Numbers with decimal points (e.g., 3.14, -2.5).
  • Strings (text): Sequences of characters (e.g., “Hello”, “Python”).

Of course, all programs rely on these basic types.

None Type

Represents the absence of a value (similar to null or nil in other languages).

logfile = None

This is often used as a placeholder for optional program settings or values.

if logfile:
    logfile.write("Some message")

Without initializing logfile to something (like None), the code above would result in an error because the variable would be undefined.

Strings (text)

Strings are fundamental for representing text-based data.

Data Structures

Real-world programs often handle more complex data arrangements.

Example: A stock holding

  • 100 shares of GOOG at $490.10

This could be represented as an “object” with three parts:

  • Name (“GOOG”, a string)
  • Number of shares (100, an integer)
  • Price (490.10, a float)

Tuples

Tuples are collections of values grouped together. They are typically used to represent simple records or data structures.

Example:

s = ('GOOG', 100, 490.10)

Tuple elements are ordered, similar to an array.

s = ('GOOG', 100, 490.10)

Tuples are particularly useful for packing and unpacking data into variables, rather than storing distinct items like you would in a list.

Packing and Unpacking

Packing multiple values into a tuple:

s = ('GOOG', 100, 490.10)

To use the tuple’s contents, you’d typically unpack it into variables:

(name, shares, price) = s

Dictionaries

Dictionaries, also known as hash tables or associative arrays, are collections of values indexed by “keys.” Think of keys as field names.

Example:

s = {
    'name': 'GOOG',
    'shares': 100,
    'price': 490.10
}

Accessing Values

Use the key names to access values:

>>> print(s['name'], s['shares'])
GOOG 100

Adding/Modifying Values

Assign values to key names to add or modify entries:

>>> s['shares'] = 75

Deleting Values

Use the del keyword:

>>> del s['date']

When to Use a Dictionary

Use a dictionary as a data structure when:

  • Your data has many different parts.
  • You need to modify or manipulate these parts.

Example: Imagine reading data from a database where each row has 50 fields. A dictionary could store the contents of each row, using descriptive field names as keys.

Containers

Programs often need to work with multiple objects – for example, a portfolio of stocks or data in spreadsheets or matrices. Python offers three primary container types:

  1. Lists (ordered data)
  2. Dictionaries (unordered data)
  3. Sets (unordered collection)

Lists as Containers

Use lists when the order of data is important. Lists can hold any type of object.

Example: A list of tuples

portfolio = [
    ('GOOG', 100, 490.10),
    ('IBM', 50, 91.10),
    ('CAT', 150, 83.44)
]

portfolio[0]  # ('GOOG', 100, 490.10)

Dictionaries as Containers

Dictionaries are useful for fast, random lookups (using key names).

Example: A dictionary of stock prices

prices = {
    'GOOG': 513.25,
    'IBM': 87.22,
    'CAT': 83.44
}

>>> prices['IBM']
87.22

Checking for Key Existence

To test if a key exists in a dictionary:

if key in d:
    # Yes
else:
    # No

Safely Looking Up Values

To look up a value that might not exist, use the get() method with a default value:

name = d.get(key, default)

Example:

>>> prices.get('IBM', 0.0)
87.22

Dictionaries and Lists

dict() can promote a list of pairs into a dictionary:

prices = dict(pricelist)

Sets

a = set([2, 3, 4])

Sets hold a collection of unordered items. They do not allow duplicates and support common set operations like union, intersection, and difference.

>>> a = set([2, 3, 4])