Python HOWTO Push a Dict on to a List (push a hash on to an array)

One of my more popular posts is How to Push a Hash on to an Array in PERL, but how do you push a dict on to a list in Python?

Lists are one-dimensional arrays and dicts are associative arrays or hash arrays.  This means we can do the same thing we do in other languages, with syntax to match Python’s object-oriented data structures.

import pprint

# Define the list
somelist = []

# Do add some elements to the list
somelist.append({'key1':'value1', 'key2': 'value2'})
somelist.append({'key1':'value1', 'key2': 'value2'})
somelist.append({'key1':'value1', 'key2': 'value2'})

# Print it out
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(somelist)

Will give you:

[   {   'key1': 'value1', 'key2': 'value2'},
{   'key1': 'value1', 'key2': 'value2'},
{   'key1': 'value1', 'key2': 'value2'}]

Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, Programming, python, Software. Bookmark the permalink.

Leave a Reply

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