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.

Related Courses:

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'}

Python tuple
Datatype casting
This entry was posted in Beginner and tagged , . Bookmark the permalink.

15 Responses to Python dictionaries

  1. Jam says:

    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.

    • Frank says:

      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 says:

    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.

    • Frank says:

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

    • Frank says:

      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]]
  3. Os says:

    yes,no,bye,my name is,=(‘Oui’, ‘Non’, ‘Au revoir’, ‘Je mappele’,) why does this not work

    • Frank says:

      Variables cannot contain spaces. This will work:

      #!/usr/bin/env python
       
      yes,no,bye,myNameIs=('Oui', 'Non', 'Au revoir', 'Je mappele',)
       
      print(yes)
      print(no)
      print(bye)
      print(myNameIs)
  4. Anuj says:
    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.

    Why does it printout in order of: ‘yes’ ‘no’ ‘hello’ ‘no’ ???

    • Frank says:

      Hi,dictionary in python do not have specific order. It’s simply a key,value mapping. See one of the comments below if you want them in order 🙂

  5. Rizwan says:

    You can also initialize this way data = {“name”:”riz”, “country”:”India”}

  6. Akash says:

    dict is keyword or variable here?

  7. Stuartjk says:

    Why in this example, does “print” output the dictionary out of any logical order?

    Ordering by input order should be – hello, yes, no, bye
    Ordering by key should be – bye, hello, no, yes
    Ordering by value should be – bye, hello, no, yes

    yet it orders – yes, bye, hello, no

    The same occurs in my own example therefore must be applying some logic to it. Understanding the logic behind this ordering may be key to interpreting the output of “print words”.

    • Frank says:

      This is by design, the dictionary data structure does not have inherent order. You can iterate through the dictionary but there is nothing to guarantee that the iteration will follow an order. You cannot sort a dictonary but you can get a representation that is sorted (in form of a list). An example:

      #!/usr/bin/python
       
      words = {}
      words["Hello"] = "Bonjour"
      words["Yes"] = "Oui"
      words["No"] = "Non"
      words["Bye"] = "Au Revoir"
       
      print words            # print key-pairs.
       
      sortList = sorted(words.items(), key=lambda x: x[1])
      print sortList

      sorted() Returns a new sorted list from the items in iterable. You could create a new dictionary from that list, but there is no guarantee that it will stay sorted.

      • Seyed Ismail says:
        {'Hello': 'Bonjour', 'Yes': 'Oui', 'No': 'Non', 'Bye': 'Au Revoir'}
        {'Hello': 'Bonjour', 'No': 'Non', 'Bye': 'Au Revoir'}
        {'Hello': 'Bonjour', 'Yes': 'Oui!', 'No': 'Non', 'Bye': 'Au Revoir'}

        It is coming like this now. Great!