Oct. 13, 2012

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
print released
{'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
print released
{'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
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, 'iphone 5': 2012,
'iphone 4': 2010}

Check the length

The len() function gives the number of pairs in the dictionary.
print len(released)

Test the dictionary

Check if a key exists in a given dictionary by using the in operator like this:
>>> my_dict = {'a' : 'one', 'b' : 'two'}
>>> 'a' in my_dict
>>> 'b' in my_dict
>>> 'c' in my_dict
or like this in a for loop
for item in released:
    if "iphone 5" in released:
        print "Key found"
        print "No keys found"
Key found

Get a value of a specified key

print released.get("iphone 3G", "none")

Print all keys with a for loop

print "-" * 10
print "iphone releases so far: "
print "-" * 10
for release in released:
    print release
iphone releases so far: 
iphone 3G
iphone 4S
iphone 3GS
iphone 5
iphone 4

Print all key and values

for key,val in released.items():
    print key, "=>", val
iphone 3G => 2008
iphone 4S => 2011
iphone 3GS => 2009
iphone => 2007
iphone 5 => 2012
iphone 4 => 2010

Get only the keys from the dictionary

phones = released.keys()
print phones
# or print them out like this:
print "This dictionary contains these keys: ", " ".join(released)
>>iphone 3G iphone 4S iphone 3GS iphone iphone 5 iphone 4
# or like this:
print "This dictionary contains these keys: ", " ", released.keys()
>>['iphone 3G', 'iphone 4S', 'iphone 3GS', 'iphone', 'iphone 5', 'iphone 4']

Printing the values

Elements may be referenced via square brackets, using the key: print released["iphone"]
print "Values:
for year in released:
    releases= released[year]
    print releases

Printing with pprint


Sorting the dictionary

for key, value in sorted(released.items()):
    print key, value

('iphone', 2007)
('iphone 3G', 2008)
('iphone 3GS', 2009)
('iphone 4', 2010)
('iphone 4S', 2011)
('iphone 5', 2012)
for phones in sorted(released, key=len):
    print phones, released[phones]
iphone 2007
iphone 5 2012
iphone 4 2010
iphone 3G 2008
iphone 4S 2011
iphone 3GS 2009


count = {}
for element in released:
    count[element] = count.get(element, 0) + 1
print count
{'iphone 3G': 1, 'iphone 4S': 1, 'iphone 3GS': 1, 'iphone': 1, 
'iphone 5': 1, 'iphone 4': 1}

Share this article

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Download Our Free Guide To Learning Python

* indicates required

Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.