根据所需的形式对python dict进行排序(但不排序)

2024-09-21 03:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这是一个非常基本的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,这样我们就可以做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吗?你知道吗


Tags: nametruetypeitemsrandomdescriptionpricedict
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是在Python2.7的标准库中引入的。如果您有较旧版本的python,您可以在ActiveState上找到有序词典的配方

collections.OrderedDict做你需要的。你知道吗

相关问题 更多 >

    热门问题