python - Accessing specific value in a list of values -


i have dictionary looks like:

{'153':  |t-shirt| |200| |0| |0|, '764': |jeans| |350| |0| |0|, '334': |hatt| |59| |0|   |0|, '324': |skor| |250| |0| |0|, '234': |tröja| |300| |0| |0|, '543': |jacka| |400| |0| |0|} 

this means example have key looks 153, access value of:

|t-shirt| |200| |0| |0| 

what if access 1 of parts in value. exampel, if type 153 , get|t-shirt| |200| |0| |0|, how access part 200 in value? if dict value is: |t-shirt| |200| |0| |0|, want get: 200, bot of other parts of same value. of dict values objects class wares, means each part enclosed "||" attribute.

for exampel:

|t-shirt| |200| |0| |0|.  

were t-shirt self.name attribute, 200 self.price attribute, 0(1st one) self.quantity , 0(2nd one) self.bought attribute.

i want access self.price attribute, how do it? tried indexing object like:

x = wares[t-shirt, 200, 0, 0] b = x[1] print(b) 

but python says that:

"object can not indexed" 

any 1 got tip?

>>> import re >>> d= {'153':  '|t-shirt| |200| |0| |0|', '764': '|jeans| |350| |0| |0|', '334': '|hatt| |59| |0|   |0|', '324': '|skor| |250| |0| |0|', '234': '|tröja| |300| |0| |0|', '543': '|jacka| |400| |0| |0|'} >>> def parts(s):         return re.findall(r'\|([^\|]+)\|', s) 

or since regex evil recommend:

>>> def parts(s):         return [x.strip('|') x in s.split()]      >>> parts(d['153']) ['t-shirt', '200', '0', '0'] >>> parts(d['153'])[1] '200' 

alternatively make things easier , more readable making parts return dictionary:

>>> def parts(s):        return dict(zip(('name', 'price', 'quantity', 'bought'), [x.strip('|') x in s.split()]))  >>> parts(d['153'])['price'] '200' 

actually make better using collections.namedtuple

>>> collections import namedtuple >>> def parts(s):         item = namedtuple('item', ('name', 'price', 'quantity', 'bought'))         return item(*[x.strip('|') x in s.split()])   >>> parts(d['153']) item(name='t-shirt', price='200', quantity='0', bought='0') >>> parts(d['153']).price '200' 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -