有这种django选择:
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
)
如何访问类别的子组(例如,获取音频选项)?我如何迭代集合?,如何直接获取叶子节点,如Vinyl?
答案 0 :(得分:1)
内置类型dict
可以从元组列表构建。
>>> MEDIA_CHOICES_D = dict(MEDIA_CHOICES)
>>> MEDIA_CHOICES_D.keys()
['unknown', 'Audio', 'Video']
>>> audio = MEDIA_CHOICES_D['Audio']
>>> audio
(('vinyl', 'Vinyl'), ('cd', 'CD'))
>>> audio_d = dict(audio)
>>> audio_d['vinyl']
'Vinyl'
>>> for k, v in audio_d.iteritems(): print '%s -> %s' % (k, v)
...
vinyl -> Vinyl
cd -> CD
>>>