Brain Goo

Carpe Crap ‘em

Brain Goo header image 2

 

 

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

April 23rd, 2010 · No Comments

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

Tags: How Tos · Programming · Software · python

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment