【发布时间】: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