How do I access dictionary keys that contain hyphens from within a Django template?

前端 未结 3 1927
执笔经年
执笔经年 2020-12-04 01:24

We have a system built on a custom database, where many of the attributes are named containing hyphens, ie:

user-name
phone-number

These pr

3条回答
  •  春和景丽
    2020-12-04 02:22

    OrderedDict dictionary types support dashes: https://docs.python.org/2/library/collections.html#ordereddict-objects

    This seems to be a side effect of the implementation of OrderedDict. Notice below that the key value pairs are actually passed in as sets. I would bet that the implementation of OrderedDict doesn't use the "key" passed in the set as a true dict key thus getting around this issue.

    Since this is a side-effect of the implementation of OrderedDict, it may not be something you want to rely on. But it works.

    from collections import OrderedDict
    
    my_dict = OrderedDict([
        ('has-dash', 'has dash value'), 
        ('no dash', 'no dash value') 
    ])
    
    print( 'has-dash: ' + my_dict['has-dash'] )
    print( 'no dash: ' + my_dict['no dash'] )
    

    Result:

    has-dash: has dash value
    no dash: no dash value
    

提交回复
热议问题