简体   繁体   English

在Django中使用OrderedDict中的字典

[英]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? 我如何在字典中使用hour_num(Julia,Kim,Anna)的值?

for trainer in trainer_dict:
     trainer.hour_5

Above code has an error: 'str' objects has no attribute 'hour_5'. 上面的代码有一个错误:'str'对象没有属性'hour_5'。

So, {{ trainer.hour_5}} show nothing in template. 因此,{{trainer.hour_5}}在模板中不显示任何内容。

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 = OrderedDict([('foo', {'a':'b'}),('bar',{'c':'d'})])会创建一个像对象一样的dict,可以像这样表示:

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() . 您可以使用my_dict.keys()my_dict.values()my_dict.items()迭代my_dict键,值和键值对。

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. 当你for trainer in trainer_dictfor trainer in trainer_dict ,训练师在这里是关键词,在你的情况下是一个字符串(训练师的名字)。 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'. 因此,为了获得存储在该键中的值,您可以执行trainer_dict[trainer] ,它将为您提供另一个词典,例如{'hour_5':'Julia','hour_1':'','hour_2','Kim'}代表'史密斯'。 Make sense? 说得通?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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