How to create a list of dictionaries?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shigehiro
    New Member
    • Oct 2006
    • 8

    How to create a list of dictionaries?

    Hi,

    I am quite new to Python & recently I have been given an assignment to create a list of dictionaries.
    Can anyone give me an idea of how to do so?

    Let say, my dictionary will have 3 keys: "FirstName" , "LastName" , and "SSID".

    So the expected output would be:
    dictList = [ {'FirstName': 'Michael', 'LastName': 'Kirk', 'SSID': '224567'},
    {'FirstName': 'Linda', 'LastName': 'Matthew', 'SSID': '123456'},
    {'FirstName': 'Sandra', 'LastName': 'Parkin', 'SSID': '123456'},
    {'FirstName': 'Bob', 'LastName': 'Henry', 'SSID': '666666'},
    {'FirstName': 'Silvia', 'LastName': 'Perkin', 'SSID': '676767'}]

    And assuming after having the above list, how can I retrieve the info of each dictionary entry?

    Thanks in advance

    Leny
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    One way is to simply use the append() function of a list.

    [CODE=python]
    >>> lst = []
    >>> lst.append({'fn ':'b','ln':'d'} )
    >>> lst.append({'fn ':'a', 'ln':'c'})
    >>> print lst
    [{'fn':'b', 'ln':'d'}, {'fn':'a', 'ln':'c'}]
    >>> for elem in lst:
    print elem['fn'], elem['ln']
    b d
    a c
    [/CODE]

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Also using the list append method similar to jlm699's post, you can do something like this:
      [code=Python]
      keys = ['FirstName', 'LastName', 'SSID']

      name1 = ['Michael', 'Kirk', '224567']
      name2 = ['Linda', 'Matthew', '123456']

      dictList = []
      dictList.append (dict(zip(keys, name1)))
      dictList.append (dict(zip(keys, name2)))

      print dictList
      for item in dictList:
      print ' '.join([item[key] for key in keys])[/code]

      Printed output:

      >>> [{'LastName': 'Kirk', 'SSID': '224567', 'FirstName': 'Michael'}, {'LastName': 'Matthew', 'SSID': '123456', 'FirstName': 'Linda'}]
      Michael Kirk 224567
      Linda Matthew 123456
      >>>

      Comment

      • jlm699
        Contributor
        • Jul 2007
        • 314

        #4
        Originally posted by bvdet
        [code=Python]
        dictList.append (dict(zip(keys, name1)))
        [/code]
        That is awesome... I never knew about zip() ... that is going to help my dictionary implementations immensely!

        Comment

        • shigehiro
          New Member
          • Oct 2006
          • 8

          #5
          Cool! Thank you so much for the replies!

          I ll try it out, shall post again if I have any further doubt.

          Shige

          Comment

          Working...