Question

I am originally a c guy but recently I started doing some stuff in python. The things that gives me trouble is the more advanced data structures in python.

I could do it all with multiple list like in c but that would just be boring right?

anyway here I have a data structure which is basically a list of dicts where the value field of the dict is another list of 2 key-value pairs:

clients = [
    {'client1':[{'test':'testvalue','status':'statusvalue'}]},
    {'client2':[{'test':'testvalue','status':'statusvalue'}]},
    {'client3':[{'test':'testvalue','status':'statusvalue'}]}
]

now I want to be able to acces the testvalue and statusvalue fields and modify or read them. based on the position in the list.

in pseudocode it would be something like:

for i in range(0,clients):
    getvalue(clients[i].'test')
    setvalue(clients[i].'test')

    getvalue(clients[i].'status')
    setvalue(clients[i].'status')

in the end I want to use this data structure to render a html page with jinja2

Was it helpful?

Solution

For a start, in Python you should (almost) never iterate over range(len(something)). You iterate over something.

Secondly, your data structure is wrong. There's no point having a list of dicts, each dict containing a single key/value pair and each value consisting of a list with a single item. You should just have a dict of dicts: you can still iterate over it.

clients = {
    'client1':{'test':'testvalue','status':'statusvalue'},
    'client2':{'test':'testvalue','status':'statusvalue'},
    'client3':{'test':'testvalue','status':'statusvalue'},
}

for key, value in clients.iteritems():
    print value['test']
    value['test'] = 'newvalue'

OTHER TIPS

I have noticed that you put a dictionary inside a list as the value for each client.

I think you may wish to re-configure your data structure as such:

clients = [
    {'client1':{'test':'testvalue','status':'statusvalue'}}
    {'client2':{'test':'testvalue','status':'statusvalue'}}
    {'client3':{'test':'testvalue','status':'statusvalue'}}
]

Therefore, you can begin iterating as such:

for client in clients:
    for k, v in client.iteritems(): #this unpacks client into 'client' (k) and {'val'...} (v)
        print v['test'] #this gets the value of test.
        v['test'] = 'some_new_value' #this sets the value of test.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top