简体   繁体   English

在 Python 中将排序列表转换为字典

[英]Converting a sorted list into dictionary in Python

I have a dictionary, say我有一本字典,说

{'name4': 380, 'name2': 349, 'name3': 290, 'name1': 294}

I have sorted the dictionary based on the values using the sorted method and the result is a list of tuples我已经使用sorted方法根据值对字典进行了sorted ,结果是一个元组列表

[('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)]

But, when I try to convert this list of tuples back to dictionary, it's back again to the old structure:但是,当我尝试将此元组列表转换回字典时,它又回到旧结构:

{'name4': 380, 'name2': 349, 'name3': 290, 'name1': 294}

I want the sorted list to be made into dictionary as it is.我希望将排序列表按原样制作成字典。 I have used dict() and manually used for loop to assign the values.我已经使用dict()并手动使用 for 循环来分配值。 But it's again leading to the same result.但它再次导致相同的结果。

Could anyone help me on this?有人可以帮我吗?

The keys in a dictionary are, because of the dictionary's underlying structure (hash map), unordered.由于字典的底层结构(哈希映射),字典中的键是无序的。 You have to order the keys yourself when you iterate the keys (ie by doing sorted(dict.keys()) or some other sorting method - if you want to sort by value, you still have to do that manually).当您迭代键时,您必须自己对键进行sorted(dict.keys()) (即通过执行sorted(dict.keys())或其他一些排序方法 - 如果您想按值排序,您仍然必须手动执行此操作)。

Instead of using an unordered dict you could use collections.OrderedDict which remembers the the insertion order:您可以使用collections.OrderedDict来记住插入顺序,而不是使用无序的dict

>>> from collections import OrderedDict
>>> odict = OrderedDict([('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)])
>>> odict
OrderedDict([('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)])

It supports the same operations like a normal dict (from the documentation of OrderedDict):它支持与普通dict相同的操作(来自 OrderedDict 的文档):

Return an instance of a dict subclass, supporting the usual dict methods.返回一个 dict 子类的实例,支持常用的 dict 方法。 An OrderedDict is a dict that remembers the order that keys were first inserted. OrderedDict 是一个 dict,它记住第一次插入键的顺序。 If a new entry overwrites an existing entry, the original insertion position is left unchanged.如果新条目覆盖现有条目,则原始插入位置保持不变。 Deleting an entry and reinserting it will move it to the end.删除一个条目并重新插入它会将它移到最后。

考虑使用一个ordered-dict,它维护有关输入键的顺序的信息。

 OrderedDict({index:i for i, index in enumerate(some_list)})

You can refer below code to print the sorted dictionary for the given data:您可以参考以下代码来打印给定数据的排序字典:

data = [('name3', 290), ('name1', 294), ('name2', 349), ('name4', 380)]

print(sorted(dict(data).items()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM