Overview
Dictionaries allow data to be stored against a unique string key. This allows for relationships between values to be stored. Notation for dictionaries is with curly brackets {}, which items separated by commas, and key and values separated by colons ":". Dictionaries do not always retain order, this is depending on which version of python you use.prices = {"apple":2.34, "pear":0.65, "chocolate": 1.34, "flour": 1.20, "eggs":2.99} print (prices)
{'apple': 2.34, 'pear': 0.65, 'chocolate': 1.34, 'flour': 1.2, 'eggs': 2.99}
Adding and Removing Items
items can be added by defining a value for a set key.prices["bread"] = 1.20 print (prices)
{'apple': 2.34, 'pear': 0.65, 'chocolate': 1.34, 'flour': 1.2, 'eggs': 2.99, 'bread': 1.2}
>
del prices["pear"] print (prices)
{'apple': 2.34, 'chocolate': 1.34, 'flour': 1.2, 'eggs': 2.99, 'bread': 1.2}
Common Methods
Two tools that help when working with dictionaries are the key() and value() methods. These create a list of keys and values, which can be useful when iterating over a dictionary.print (prices.keys()) print (prices.values())
dict_keys(['apple', 'chocolate', 'flour', 'eggs', 'bread']) dict_values([2.34, 1.34, 1.2, 2.99, 1.2])
Related Sections
Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.
Related Pages
Pickle - The pickle library allows a program to save data in a binary file.Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines