How to Create a Dictionary in Python
In the Python programming language, a dictionary is a data structure that maps unique keys to values. In other programming languages, however, these data structures are known associative arrays or hashes. Each key in a Python dictionary is unique and has a one-to-one relationship with an associated value. The values associated with the keys do not have to be unique, that is, multiple keys can map to the same value, but not the each key itself can only map to one value.
Instructions
-
-
1
Type in a series of key/value pairs, separated by commas and enclosed in curly braces to create a literal dictionary. A dictionary in Python can be a literal or it can be assigned to a variable. The key and value in the pair are separated by colons. Here is an example: {"Python":"dictionary", "Ruby":"hash", "Java":"Hashtable"}
-
2
Assign a reference to a dictionary object to a variable by using the assignment operator (=). This is no different than you would do to assign any other value to a variable. d = {"Python":"dictionary", "Ruby":"hash", "Java":"Hashtable"}
-
-
3
Return the value mapped to a key in a dictionary by typing the variable name that references the dictionary, followed by the key. The key needs to be enclosed in brackets. This example will return the string "dictionary" and assign that string to the variable structure_name. structure_name = d["Python"]
-
4
Add key/value pairs to a Python dictionary. Type the variable name that references the dictionary, followed by the key that you wish to associate with a value (enclosed in brackets), then use the assignment operator = to associate a value to the key: d["Elephant"] = "mammal"
-
5
Use a string object as a key that maps to a value that is an integer, or use an integer object as a key that maps to a list object. x = {"Python":"dictionary", "meaning":42, 1134:["one", "two", "three"]}
-
6
Assign new value to a key in a dictionary to wipe out the old value and replace it with the new one. Here, the key string "Elephant" is mapped to the string value "mammal", then it is changed to map to the string value "big". This does not create two entries in the dictionary. The second association using the same key "Elephant" replaces the old value with a new one. d["Elephant"] = "mammal" d["Elephant"] = "big"
-
1
Tips & Warnings
A Python dictionary can use any type of object for the keys and values. The types used for the keys and values do not have to be the same throughout the data structure.