by
0
6
3,259
1
Top 1% !
Popular
Famous
Tagged
Specified
OpenSource
Popularity: 3884th place
Created
Modified Sep 24, 2013

Published on:

Architecturex86_64
LanguagePython
LicenseMIT_X11

Define and manage custom objects in python

This simple snippet shows how to define a basic custom object ('myInfo') and how to manage it into a dictionary.

You can define the object's attributes and reference to them while accessing the data.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/11235/Define-and-manage-custom-objects-in-pyth?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
#Initialize dictionary myDict = dict() # Assume we have a list populated with some data for info in someList: # Iterate through items in list. # Assume to get value at index 0,1,2,3 as example data = info[0] # Build a new object to be added in dictionary myInfo = { 'id' : info[1] , 'name' : info[2] , 'value' : info[3], 'data' : data, } # Populate the dictionary myDict.setdefault(data,[]).append(myInfo) # Loop through all dictionary items and print # accessing each object's property for key in myDict: print "key="+key for data in myDict[key]: print "id = "+str(data['id']) print "name = "+str(data['name']) print "value = "+str(data['value']) print "data = "+str(data['data'])
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus