How Do You Use a Dictionary in Python?

Problem scenario
You want to use a dictionary in Python, but you do not know how. What should you do?

Solution
1.  For a very simple dictionary, you could use "{}" with no quotes.  This makes var1 a dictionary in Python:

var1 = {}

Normally with no colons, two matching curly braces would signify a set.  (You can find out more about this Python syntax here.)

2.  To really learn about dictionaries, create a file called test.py with the following content:

# The two lines below show how to create two dictionaries
dict1 = { 1:'Mark Zuckerberg', 2:'Sheryl Sandberg'}
dict2 = { 2:'Sheryl Sandberg', 1:'Mark Zuckerberg'}

# This if clause demonstrates testing the equivalence of the two dictionaries
if dict1 == dict2:
  print 'The contents of the dictionaries are identical!'
else:
  print 'The contents of the dictionaries are dissimilar.'

# This line demonstrates adding a key-value pair to a dictionary
dict1['Peter Thiel'] = 3
# This proves that dictionaries are mutable.
print dict1

3.  Run the program test.py (using python test.py) to see how Python dictionaries work.

Leave a comment

Your email address will not be published. Required fields are marked *