Python dictionaries


A dictionary can be thought of as an unordered set of key: value pairs.

A pair of braces creates an empty dictionary: {}.  Each element can maps to a certain value.  An integer or string can be used for the index. Dictonaries do not have an order.

Video: Dictionary Get PDF Get Exercises Quiz

Dictionary example

Let us make a simple dictionary:

#!/usr/bin/python
 
words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"
 
print(words["Hello"])
print(words["No"])

Output:

Bonjour
Non

We are by no means limited to single word defintions in the value part. A demonstration:

#!/usr/bin/python
 
dict = {}
dict['Ford'] = "Car"
dict['Python'] = "The Python Programming Language"
dict[2] = "This sentence is stored here."
 
print(dict['Ford'])
print(dict['Python'])
print(dict[2])

Output:

Car
The Python Programming Language
This sentence is stored here.

Manipulating the dictionary

We can manipulate the data stored in a dictionairy after declaration.  This is shown in the example below:

#!/usr/bin/python
 
words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"
 
print(words)           # print key-pairs.
del words["Yes"]       # delete a key-pair.
print(words)           # print key-pairs.
words["Yes"] = "Oui!"  # add new key-pair.
print(words)           # print key-pairs.

Output:

{'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Yes': 'Oui!', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}


15 thoughts on “Python dictionaries

  1. Jam - July 14, 2016

    hi,
    I am a new learner of Python, and confused of single quotation(‘ ‘) and double quotation(” “) marks.
    here is an example:

    words = {}
    words["Hello"] = "Bonjour"
    words["Yes"] = "Oui"
    words["No"] = "Non"
    words["Bye"] = "Au Revoir"
     
    print words            # print key-pairs.
    Output:
    {'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}

    So, why the output is not {Yes: Oui, Bye: Au Revoir, Hello: Bonjour, No: Non} ?
    And what’s the difference between this two definitions, does( ” ” ) means TWO( ‘ ‘ ) ?

    words["Hello"] = "Bonjour"  #double quotation 
    words['Hello'] = "Bonjour"     #single quotation

    Thanks.

    1. Frank - July 15, 2016

      There is no specific difference between single and double quotation in the Python language, it’s just a matter of preference. Python supports single, double and triple quotes. Output is always single quotes

  2. Jacco Van Dorp - November 11, 2015

    I’ve got a little problem which I believe originates from my lack of understanding of dictionaries. Here’s a slimmed down version of my code;

    class Sensor:
    	name= ""
    	iteration = 0
    	data= []
     
    	def __init__(self, name):
    		self.name = name
     
    	def writedata(self, data=[0,0,0,0]):
    		self.data.append(data)
    		self.iteration = self.iteration + 1
     
    def report(dict):
    	name = {}
    	iteration = {}
    	data = {}
    	for i in dict:
    		name[i] = dict[i].name
    		data[i] = dict[i].data
    		iteration[i] = dict[i].iteration
    	print("Report:")
    	for i in dict:
    		print("Name: " + name[i] + " Iteration: " + str(iteration[i]))
    		for j in data[i]:
    			print (j)

    After which I run the following:

    foo = {}
    foo["ID0"] = Sensor("ID0")
    foo["ID1"] = Sensor("ID1")
    report(foo)
    foo["ID0"].writedata([0,1,2,3])
    foo["ID0"].writedata([5,6,7,8])
    report(foo)
    foo["ID1"].writedata([10,11,12,13])
    foo["ID1"].writedata([15,16,17,18])
    report(foo)

    So what I’m basically doing is using this dictionary to store my different instances of the Sensor class. however, when I progress their methods, they seem to append the data lists to all instances of the Sensor class, not just the one specified. The output from the last report looks like this:

    Report:
    Name: ID1 Iteration: 2
    [0, 1, 2, 3]
    [5, 6, 7, 8]
    [10, 11, 12, 13]
    [15, 16, 17, 18]
    Name: ID0 Iteration: 2
    [0, 1, 2, 3]
    [5, 6, 7, 8]
    [10, 11, 12, 13]
    [15, 16, 17, 18]

    One of the weird things happening here is that the Iteration count does seem to update only at the specified instance of Sensor, whereas the data modifications applies to all of them. Do you have any idea what I’m doing wrong?

    Thanks for your time in advance.

    1. Frank - November 13, 2015

      Things have been pretty busy, I’ll reply to you as soon as I get the chance.

    2. Frank - November 20, 2015

      Hi, sorry for the late reply, it’s been extremely busy at my job. You are right. Both objects contain the list [[0, 1, 2, 3], [5, 6, 7, 8], [10, 11, 12, 13], [15, 16, 17, 18]]. Initializing the list in the constructor seems to solve the issue. Add the line self.data = [] in the constructor.

      class Sensor:
          name= ""
          iteration = 0
          data= []
       
          def __init__(self, name):
              self.name = name
              self.data = []
       
          def writedata(self, data=[0,0,0,0]):
              self.data.append(data)
              self.iteration = self.iteration + 1
       
      def report(dict):
          name = {}
          iteration = {}
          data = {}
       
          for i in dict:
              name[i] = dict[i].name
              data[i] = dict[i].data
              iteration[i] = dict[i].iteration
              print("Report:")
       
          for i in dict:
              print("Name: " + name[i] + " Iteration: " + str(iteration[i]))
       
          for j in data[i]:
              print (j)
       
      foo = {}
      foo["ID0"] = Sensor("ID0")
      foo["ID1"] = Sensor("ID1")
      report(foo)
      foo["ID0"].writedata([0,1,2,3])
      foo["ID0"].writedata([5,6,7,8])
      report(foo)
      foo["ID1"].writedata([10,11,12,13])
      foo["ID1"].writedata([15,16,17,18])
      report(foo)
       
       
      print "\nFinal situation:\n"
      for i in foo:
          print foo[i].name, foo[i].data

      Output:

      Report:
      Report:
      Name: ID0 Iteration: 0
      Name: ID1 Iteration: 0
      Report:
      Report:
      Name: ID0 Iteration: 2
      Name: ID1 Iteration: 0
      Report:
      Report:
      Name: ID0 Iteration: 2
      Name: ID1 Iteration: 2
      [10, 11, 12, 13]
      [15, 16, 17, 18]
       
      Final situation:
       
      ID0 [[0, 1, 2, 3], [5, 6, 7, 8]]
      ID1 [[10, 11, 12, 13], [15, 16, 17, 18]]