简体   繁体   中英

using dictionary in OrderedDict in Django

trainer_dict = OrderedDict([('Smith', {'hour_5':'Julia','hour_1':'','hour_2','Kim'}),('Sam',{'hour_5':'','hour_1':'Anna','hour_2',''})])

How I use the value of hour_num (Julia, Kim, Anna) in the dictionary?

for trainer in trainer_dict:
     trainer.hour_5

Above code has an error: 'str' objects has no attribute 'hour_5'.

So, {{ trainer.hour_5}} show nothing in template.

for trainer in trainer_dict:
     trainer['hour_5'] 

has also an error: string indices must be integers.

There is a dictionary in [()]. How I access the dictionary??

Try this:

for trainer, training in trainer_dict.items():
     training['hour_5']

my_dict = OrderedDict([('foo', {'a':'b'}),('bar',{'c':'d'})]) will create a dict like object which can be represented like this:

my_dict = {
    'foo': {'a': 'b'},
    'bar': {'c': 'd'}
}

You can iterate over keys, values and key-value pairs of my_dict using my_dict.keys() , my_dict.values() and my_dict.items() .

Hope it helps

When you do for trainer in trainer_dict the trainer here is the key in the dict , that is a string (name of the trainer) in your case. So in order to get the value stored at that key you can do trainer_dict[trainer] that will give you the the another dict for example {'hour_5':'Julia','hour_1':'','hour_2','Kim'} for the name 'Smith'. Make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM