Search code examples
pythonobjectdictionaryvaluestack

Accessing specific value in a list of values


I have a dictionary that 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 that I for example have a key that looks like 153, which access a value of:

|T-shirt| |200| |0| |0|

What if I would like to do is access 1 of the parts in my value. For exampel, if i type 153 and get|T-shirt| |200| |0| |0|, how then to access the part 200 in my value? If my dict value is: |T-shirt| |200| |0| |0|, i want only to get: 200, bot any of the other parts of the same value. All of my dict values are objects for the class wares, which means that each part that is enclosed by "||" is a attribute.

for exampel:

|T-shirt| |200| |0| |0|. 

Were T-shirt is a self.name attribute, 200 is a self.price attribute, 0(1st one) is a self.quantity and 0(2nd one) is a self.bought attribute.

I only want to access the self.price attribute, how do I do it? I tried indexing my object like:

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

but python says that:

"object can not be indexed"

any one got a tip?


Solution

  • >>> 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 is evil I would recommend:

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

    Alternatively you could make things much easier and more readable by making parts return a dictionary:

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

    Actually we could make this even better using collections.namedtuple

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