Archived:List of Dictionaries in Python
All PySymbian articles have been archived. PySymbian is no longer maintained by Nokia and is not guaranteed to work on more recent Symbian devices. It is not possible to submit apps to Nokia Store.
Article Metadata
Contents |
List of Dictionaries
List and Dictionary are two very useful concepts in Python to manipulate data at various levels. The article shows how the combined features of a List and a Dictionary can provide additional coding advantages that single List or a single Dictionary cannot. The idea is to create a List object that has elements as Dictionary in place of normal string,integers or even variables.
l=[dict1,dict2,dict2,dict3,...]
l=[{},{},{},{},{}]
Advantages
The list of dictionaries provide easy database type structure. The list elements,i.e the dictionaries have various keys which can be treated as database field. The dictionary values corresponding to the particular keys are the field values of the database object.
Example
Following is the example of list of dictionaries forming a Database of customers.
cust= [{"id":1,"name":u"name 1","bill_amount":1000},
{"id":1,"name":u"name 2","bill_amount":5000},
{"id":3,"name":u"name 3","bill_amount":7600},
{"id":1,"name":u"name 4","bill_amount":30}
]
Accessing object attributes
Each of the database object can be accessed with dictionary and list coding conventions.
Listing the fields
The following code will print the id, name and bill amount of each customer.
for x in cust:
print x["id"], x["name"], x["bill_amount"]
Deleting Entire Field
The entire database field can be removed by the statement,
for x in cust:
del x["id"]
Above code will delete id field of each entry.
Adding New Field
The new field in each entry can be inserted by the statement,
for x in cust:
x["new_field"]=123 ##any initial value
The code will add field new_field to each entry.
Modifying Entry
The fields value can be modified at any level with statement,
cust[2]["name"]=u"xyz"
It will change the name of customer 3 to xyz.
Deleting an Entry
The entire entry can be deleted by following code,
del cust[3]
It will delete the customer4 from the list.
Related Links
--ck.umraliya 16:57, 1 October 2008 (EEST)


(no comments yet)