I am a n00b to Python and am attempting to bring the little bit of knowledge I have from shell and PHP scripting to Python. I really trying to grasp the concepts of creating and manipulating the values within (while keeping the code in an understandable form).
I am having trouble utilizing the Python implementations of LISTS and MAPPINGS ( dict() ). I am writing a script that needs to use an associative array (a python mapping) inside of a basic array (a Python list). The list can use the typical INT index.
Thanks!
Here is what I have currently:
''' Marrying old-school array concepts
[in Python verbiage] a list (arr1) of mappings (arr2)
[per my old-school training] a 2D array with
arr1 using an INT index
arr2 using an associative index
'''
arr1 = []
arr1[0] = dict([ ('ticker'," "),
('t_date'," "),
('t_open'," "),
('t_high'," "),
('t_low'," "),
('t_close'," "),
('t_volume'," ")
] )
arr1[1] = dict([ ('ticker'," "),
('t_date'," "),
('t_open'," "),
('t_high'," "),
('t_low'," "),
('t_close'," "),
('t_volume'," ")
] )
arr1[0]['t_volume'] = 11250000
arr1[1]['t_volume'] = 11260000
print "\nAssociative array inside of an INT indexed array:"
print arr1[0]['t_volume'], arr1[1]['t_volume']
In PHP, I have the following example working:
'''
arr_desired[0] = array( 'ticker' => 'ibm'
't_date' => '1/1/2008'
't_open' => 123.20
't_high' => 123.20
't_low' => 123.20
't_close' => 123.20
't_volume' => 11250000
);
arr_desired[1] = array( 'ticker' => 'ibm'
't_date' => '1/2/2008'
't_open' => 124.20
't_high' => 124.20
't_low' => 124.20
't_close' => 124.20
't_volume' => 11260000
);
print arr_desired[0]['t_volume'],arr_desired[1]['t_volume'] # should print>>> 11250000 11260000
'''
Your list and dict literal definitions can be much simplified:
I’m using the
dict.fromkeys()method to initialize a dict with a sequence of keys, all with a given default value (a one-space string).When you define an empty list in Python, you cannot simply address elements that don’t exist. Alternatively, use the
.append()method to add new elements to a list:The above example uses the
{k: v}dict literal notation.I suspect you would benefit from reading the (excellent) Python tutorial first.