Python:元组提取列表的对象

时间:2020-02-19 11:12:34

标签: python django

我有一个以下格式的对象:

{
  'af': {
    'bidi': False, 
    'code': 'af', 
    'name': 'Afrikaans', 
    'name_local': 'Afrikaans'
  },
  'ar': {
    'bidi': True, 
    'code': 'ar', 
    'name': 'Arabic', 
    'name_local': 'العربيّة'
  },
  ...
}

这是django.conf.locale.LANG_INFO中的语言环境列表。 (有关完整参考,请参见此处:https://github.com/django/django/blob/master/django/conf/locale/init.py)。

现在,我希望在模型类中使用此列表:

locale = models.CharField(max_length=5, choices=get_locale_choices(), default='en')

我具有以下实用程序功能:

from django.conf.locale import LANG_INFO

def get_locale_choices():
    return ?

现在,返回的?应该是以下格式:

[
    ('af', 'Afrikaans'),
    ('ar', 'Arabic'),
    ...
]

我的问题是,我该如何将LANG_INFO词典变成上面的元组列表?

感觉像这样的事情已经结束了:

a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
d_items = a_dict.items()
d_items  # Here d_items is a view of items
dict_items([('color', 'blue'), ('fruit', 'apple'), ('pet', 'dog')])

但是...嗯,不确定吗?我想从关键项中提取一个子值...

1 个答案:

答案 0 :(得分:3)

使用列表理解:

from django.conf.locale import LANG_INFO

def get_locale_choices():
    return [(k, v['name']) for k, v in LANG_INFO.items() if 'name' in v]

... if 'name' in v部分对于确保具有'fallback'但没有'name'的案件(例如zh-cnzh-my,{{1} }等)。

结果:

zh-sg

注意:[('af', 'Afrikaans'), ('ar', 'Arabic'), ...] 似乎是Django内部的,所以您对它的使用未得到Django的正式批准。