如何使用另一个列表作为键的引用来更改Python 3.5词典中的键顺序?

时间:2018-09-02 16:51:40

标签: python dictionary key

我试图更改字典中“键”的顺序,但没有成功。 这是我最初的字典:

Not_Ordered={
  'item':'book',
  'pages':200, 
  'weight':1.0, 
  'price':25, 
  'city':'London'
}

我是否有机会根据按键顺序列表更改顺序,如下所示:

key_order=['city', 'pages', 'item', 'weight', 'price']

注意:

  • 我正在使用Python 3.5.2。
  • 我不是要对键进行排序。
  • 我知道在插入后将插入Python 3.6。
  • 我也知道OrderedDict,但是它给了我一个列表,但是我 寻找字典作为最终结果。

4 个答案:

答案 0 :(得分:2)

从3.7开始,将按照插入顺序“正式”维护字典。它们在3.6中如此订购,但在3.7之前并不能保证。在3.6之前的版本中,您无法执行任何操作来影响按键的显示顺序。

但是可以使用OrderedDict代替。我不理解您的“反对,但它给了我一个清单”反对意见-我看不出这是真的。

您的示例:

>>> from collections import OrderedDict
>>> d = OrderedDict([('item', 'book'), ('pages', 200),
...                  ('weight', 1.0), ('price', 25),
...                  ('city', 'London')])
>>> d # keeps the insertion order
OrderedDict([('item', 'book'), ('pages', 200), ('weight', 1.0), ('price', 25), ('city', 'London')])
>>> key_order= ['city', 'pages', 'item', 'weight', 'price'] # the order you want
>>> for k in key_order: # a loop to force the order you want
...     d.move_to_end(k)
>>> d # which works fine
OrderedDict([('city', 'London'), ('pages', 200), ('item', 'book'), ('weight', 1.0), ('price', 25)])

不要被输出格式所迷惑!为了清楚起见,{em}显示{em}作为对的列表,并传递给d构造函数。 OrderedDict本身不是列表。

答案 1 :(得分:1)

您的问题是Python中的字典没有插入顺序,因此您无法对其进行“排序”。如您在此处看到的:Official Python Docs on Dictionaries。 如果您对此目的有更多了解,我们可能会尝试以其他方式解决它。

答案 2 :(得分:0)

Python 3.5中没有解决方案


对于python> = 3.6,仅

k = {k : Not_Ordered[k] for k in key_order}

答案 3 :(得分:0)

您仍然可以使用sorted并指定items()。

ordered_dict_items = sorted(Not_Ordered.items(), key=lambda x: key_order.index(x[0]))  
return dict((x, y) for x, y in ordered_dict_items) # to convert tuples to dict

或直接使用列表:

ordered_dict_items = [(k, Not_Ordered[k]) for k in key_order]
return dict((x, y) for x, y in ordered_dict_items) # to convert tuples to 
相关问题