Re: Please provide a better explanation of tuples and dictionaries

Discussion in 'Python' started by John Gordon, Jan 30, 2013.

  1. John Gordon

    John Gordon Guest

    In <> "Daniel W. Rouse Jr." <> writes:

    > I have recently started learning Python (2.7.3) but need a better
    > explanation of how to use tuples and dictionaries.


    A tuple is a linear sequence of items, accessed via subscripts that start
    at zero.

    Tuples are read-only; items cannot be added, removed, nor replaced.

    Items in a tuple need not be the same type.

    Example:

    >>> my_tuple = (1, 5, 'hello', 9.9999)
    >>> print my_tuple[0]

    1
    >>> print my_tuple[2]

    hello

    A dictionary is a mapping type; it allows you to access items via a
    meaningful name (usually a string.)

    Dictionaries do not preserve the order in which items are created (but
    there is a class in newer python versions, collections.OrderedDict, which
    does preserve order.)

    Example:

    >>> person = {} # start with an empty dictionary
    >>> person['name'] = 'John'
    >>> person['age'] = 40
    >>> person['occupation'] = 'Programmer'
    >>> print person['age']

    40

    Dictionaries can also be created with some initial values, like so:

    >>> person = { 'name': 'John', 'age': 40, 'occupation' : 'Programmer' }


    --
    John Gordon A is for Amy, who fell down the stairs
    B is for Basil, assaulted by bears
    -- Edward Gorey, "The Gashlycrumb Tinies"
     
    John Gordon, Jan 30, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris Angelico
    Replies:
    1
    Views:
    117
    Chris Angelico
    Jan 30, 2013
  2. Mitya Sirenef
    Replies:
    0
    Views:
    107
    Mitya Sirenef
    Jan 30, 2013
  3. rusi
    Replies:
    0
    Views:
    117
  4. Rick Johnson
    Replies:
    2
    Views:
    126
    Chris Angelico
    Feb 3, 2013
  5. Jon Reyes
    Replies:
    18
    Views:
    245
    Mitya Sirenef
    Feb 19, 2013
Loading...

Share This Page