How to use dictionaries in Python

This post will explain how to use dictionaries in Python.

About dictionaries in Python

Use {} curly brackets to construct the dictionary, and [] square brackets to index it. Separate the key and value with colons : and with commas , between each pair. Keys must be quoted As with lists we can print out the dictionary by printing the reference to it. A dictionary maps a set of objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys to values. Dictionaries are mutable, which means they can be changed. The values that the keys point to can be any Python value. Dictionaries are unordered, so the order that the keys are added doesn’t necessarily reflect what order they may be reported back.

Create a new dictionary

# In order to construct a dictionary you can start with an empty one. >>> mydict={} # This will create a dictionary, which has an initially six key-value pairs, where iphone* is the key and years the values

released = {
		"iphone" : 2007,
		"iphone 3G" : 2008,
		"iphone 3GS" : 2009,
		"iphone 4" : 2010,
		"iphone 4S" : 2011,
		"iphone 5" : 2012
	}
>>Output
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, '
	iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}

Add a value to the dictionary

You can assign to an individual dictionary entry to add it or modify it

#the syntax is: mydict[key] = "value"
released["iphone 5S"] = 2013
>>Output
{'iphone 5S': 2013, 'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009,
'iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}

Remove a key and it’s value

You can remove key-value pairs with the del operator

del released["iphone"]
print released
>>output
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, 'iphone 5': 2012,
'iphone 4': 2010}