Home arrow Python arrow Dictionaries, Variables and Statements in Python

Dictionaries, Variables and Statements in Python

In this third part of a nine-part series that quickly goes over the Python language, you will learn about dictionaries, references, and much more. It is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Copyright 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Dictionaries, Variables and Statements in Python
  2. Variables and Other References
  3. Assignment Statements
  4. Augmented assignment
By: O'Reilly Media
Rating: starstarstarstarstar / 2
September 25, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Dictionaries 

A mapping is an arbitrary collection of objects indexed by nearly arbitrary values called keys. Mappings are mutable and, unlike sequences, are not ordered.

Python provides a single built-in mapping type, the dictionary type. Library and extension modules provide other mapping types, and you can write others
yourself (as discussed in "Mappings" on page 110). Keys in a dictionary may be of different types, but they must be hashable (see hash on page 162). Values in a dictionary are arbitrary objects and may be of different types. An item in a dictionary is a key/value pair. You can think of a dictionary as an associative array (known in other languages as a "map," "hash table, or "hash").

To specify a dictionary, you can use a series of pairs of expressions (the pairs are the items of the dictionary) separated by commas (,) within braces ({}). You may optionally place a redundant comma after the last item. Each item in a dictionary is written as key:value , where key  is an expression giving the item's key and value  is an expression giving the item's value. If a key appears more than once in a dictionary literal, only one of the items with that key is kept in the resulting
dictionary object--dictionaries do not allow duplicate keys. To denote an empty dictionary, use an empty pair of braces. Here are some dictionaries:

  {'x':42, 'y':3.14, 'z':7 }    # Dictionary with three items and string keys
  {1:2, 3:4 }                   # Dictionary with two items and integer keys
  {}                            # Empty dictionary

You can also call the built-in type dict to create a dictionary in a way that, while less concise, can sometimes be more readable. For example, the dictionaries in this last snippet can also, equivalently, be written as, respectively:

  dict(x=42, y=3.14, z=7)       # Dictionary with three items and string keys
  dict([[1, 2], [3, 4]])        # Dictionary with two items and integer keys
  dict()                        # Empty dictionary

dict() without arguments creates and returns an empty dictionary. When the argument x to dict is a mapping, dict returns a new dictionary object with the same keys and values as x . When x  is iterable, the items in x  must be pairs, and dict(x) returns a dictionary whose items (key/value pairs) are the same as the items in x . If a key appears more than once in x , only the last item with that key is kept in the resulting dictionary.

When you call dict, in addition to or instead of the positional argument x  you may pass named arguments, each with the syntax name=value , where name  is an identifier to use as an item's key and value  is an expression giving the item's value. When you call dict and pass both a positional argument and one or more named arguments, if a key appears both in the positional argument and as a named argument, Python associates to that key the value given with the named argument (i.e., the named argument wins).

You can also create a dictionary by calling dict.fromkeys. The first argument is an iterable whose items become the keys of the dictionary; the second argument is the value that corresponds to each key (all keys initially have the same corresponding value). If you omit the second argument, the value corresponding to each key is None. For example:

  dict.fromkeys('hello', 2)    # same as {'h':2, 'e':2, 'l':2, 'o':2}
  dict.fromkeys([1, 2, 3])     # same as {1:None, 2:None, 3:None}

None

The built-in None denotes a null object. None has no methods or other attributes. You can use None as a placeholder when you need a reference but you don't care what object you refer to, or when you need to indicate that no object is there. Functions return None as their result unless they have specific return statements coded to return other values.

Callables

In Python, callable types are those whose instances support the function call operation (see "Calling Functions" on page 73). Functions are callable. Python provides several built-in functions (see "Built-in Functions" on page 158) and supports user-defined functions (see "The def Statement" on page 70). Generators are also callable (see "Generators" on page 78).

Types are also callable, as we already saw for the dict, list, and tuple built-in types. (See "Built-in Types" on page 154 for a complete list of built-in types.) As we'll discuss in "Python Classes" on page 82, class objects (user-defined types) are also callable. Calling a type normally creates and returns a new instance of that type.

Other callables are methods, which are functions bound to class attributes and instances of classes that supply a special method named __call__.

Boolean Values

Every data value in Python can be taken as a truth value: true or false. Any nonzero number or nonempty container (e.g., string, tuple, list, set, or dictionary) is true. 0 (of any numeric type), None, and empty containers are false. Be careful about using a floating-point number as a truth value: such use is equivalent to comparing the number for exact equality with zero, and floating-point numbers should almost never be compared for exact equality!

Built-in type bool is a subclass of int. The only two values of type bool are True and False, which have string representations of 'True' and 'False', but also numerical values of 1 and 0, respectively. Several built-in functions return bool results, as do comparison operators. You can call bool(x) with any x as the argument. The result is True if x  is true and False if x  is false. Good Python style is not to use such calls when they are redundant: always write if x:, never if bool(x):, if x==True:, if
bool(x)==True
, and so on.



 
 
>>> More Python Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: