【问题标题】:Order(but not sort) a python dict according to required format根据所需格式订购(但不排序)python dict
【发布时间】:2015-07-15 06:38:06
【问题描述】:

我知道这是一个非常基本的 python 概念,但感觉它对某人有用。

我有以下列表

list_items = [
 ('name','Random'),
 ('type','Film'),
 ('description','Nothing'),
 ('rent_active','True'),
 ('rent_price_usd','23.4'),
 ('rent_price_episode_usd','23.4'),
 ('buy_episode_active','23.4'),

]

现在我想把它转换成字典,所以我们可以做dict(list_items),结果是

{'buy_episode_active': '23.4',
 'description': 'Nothing',
 'name': 'Random',
 'rent_active': 'True',
 'rent_price_episode_usd': '23.4',
 'rent_price_usd': '23.4',
 'type': 'Film'}

但我需要的是字典中的项目应该与上面列表中的项目(list_items)中的项目顺序相同,如下所示

{
 'name': 'Random',
 'type': 'Film'
 'description': 'Nothing',
 'rent_active': 'True',
 'rent_price_usd': '23.4',
 'rent_price_episode_usd': '23.4',
 'buy_episode_active': '23.4',
 }

我知道列表是有序的元素集合,而字典是无序的元素集合,但我仍然需要上述所需格式的字典,如果我们对列表进行额外处理或处理需要时间,我可以。那么任何人都可以告诉我如何根据我们所需的格式订购 dict 吗?

【问题讨论】:

  • “我还需要上述格式的字典” - 为什么?
  • 嗯,有人需要按照这种格式读取的dict
  • ...为什么?如果可读性很重要,字典是最好的工具吗?你能写一个函数来显示一个定义了键顺序的字典吗?如果不了解您的问题,就很难以最佳方式解决它。

标签: python list sorting dictionary


【解决方案1】:

collections.OrderedDict 满足您的需求。

【讨论】:

    【解决方案2】:

    使用collections.OrderedDict

    >>> list_items = [
    ...  ('name','Random'),
    ...  ('type','Film'),
    ...  ('description','Nothing'),
    ...  ('rent_active','True'),
    ...  ('rent_price_usd','23.4'),
    ...  ('rent_price_episode_usd','23.4'),
    ...  ('buy_episode_active','23.4'),
    ... ]
    >>> from collections import OrderedDict
    >>> mydict = OrderedDict(list_items)
    >>> mydict
    OrderedDict([('name', 'Random'), ('type', 'Film'), ('description', 'Nothing'), ('rent_active', 'True'), ('rent_price_usd', '23.4'), ('rent_price_episode_usd', '23.4'), ('buy_episode_active', '23.4')])
    

    请注意,OrderedDict 在 python 2.7 中被引入标准库。如果你有旧版本的 python,你可以在ActiveState找到有序字典的食谱

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2013-06-10
      • 2017-12-17
      • 2011-03-31
      • 2019-11-14
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      相关资源
      最近更新 更多