Python
  Home arrow Python arrow Dictionaries, Variables and Statements...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Dictionaries, Variables and Statements in Python
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-09-25

    Table of Contents:
  • Dictionaries, Variables and Statements in Python
  • Variables and Other References
  • Assignment Statements
  • Augmented assignment

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Dictionaries, Variables and Statements in Python


    (Page 1 of 4 )

    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.

    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


       · This article is an excerpt from the book "Python in a Nutshell, Second Edition,"...
     

    Buy this book now. This article is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Check it out today at your favorite bookstore. Buy this book now.

       

    PYTHON ARTICLES

    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT