logo

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 Course:
Complete Python Bootcamp: Go from zero to hero in Python 3

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

Download Python Exercises

BackNext

15 thoughts on “Python dictionaries


  1. 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]]

  2. Os
    - August 26, 2015

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

    1. Frank
      - August 26, 2015

      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)

  3. Anuj
    - July 15, 2015
    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’ ???

    1. Frank
      - July 15, 2015

      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 🙂

  4. Rizwan
    - July 11, 2015

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

  5. Akash
    - June 5, 2015

    dict is keyword or variable here?

    1. Frank
      - June 5, 2015

      In the example dict is a variable that you can access. But dictionaries as a datastructure is available in python

  6. Stuartjk
    - May 11, 2015

    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”.

    1. Frank
      - May 11, 2015

      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.

      1. Seyed Ismail
        - June 15, 2015
        {'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!

Leave a Reply

Login disabled