How to Construct a Dictionary in Python

A dictionary is one of the Python object types that seems unusual to non-Python programmers. A dictionary is a type of object known as a "mapping" -- a collection of other objects, stored by key instead of by sequence or relative position. Dictionaries are mutable, can be changed in place, and can grow and shrink as needed. In this regard, they are similar to lists.

Instructions

    • 1

      Start a Python script, either in a text editor, using IDLE, or in the command line.

      To start a Python script using a text editor, such as Emacs, Vim or TextWrangler, start the editor and create a new file. Save the file as "dictionary.py" and begin typing.

      To create a new script with IDLE (Python's built-in development environment, open IDLE. On a Mac, click "Applications," followed by "Python 2.x" and then "IDLE." In Windows, click the "Start" menu. Click "Programs," followed by "Python 2.x" and then "IDLE (Python GUI.)"

      To start Python from the command line, simply type "python" at the command prompt.

    • 2

      Create a dictionary. Dictionaries are constructed using curly braces ({ }) and colons. As an example:

      D = { 'food' : 'spam', x : 'four', 'color' : 'pink'}

    • 3

      Recall your dictionary values using their corresponding keys. To continue the example,

      print D ['food']

      returns

      "spam"

    • 4

      Change your dictionary entries according to key. You can type

      D [ 'color'] = 'blue'

      and the "color" key in D will change accordingly. You may also type

      D [ 'quantity'] = 'fifty'

      and D will update to include a key called "quantity" with the value "fifty."

Related Searches:

References

Comments

Related Ads

Featured