简体   繁体   English

如何按命名值对 Python 字典进行排序

[英]How do I sort a Python Dictionary by a named value

I have a dictionary 'dict' like so:我有一个像这样的字典“dict”:

{'Name1' : {'value1' : 3.0, 'value2' : 1.4, 'Index' : 2 },  
 'Name2' : {'value1' : 5.0, 'value2' : 0.1, 'Index' : 1 },  
 ...
}

How would I sort the dictionary into a new one, based on the 'Index' field?我将如何根据“索引”字段将字典分类为新字典? So I want to end up as:所以我想最终成为:

{'Name2' : {'value1' : 5.0, 'value2' : 0.1, 'Index' : 1 },  
 'Name1' : {'value1' : 3.0, 'value2' : 1.4, 'Index' : 2 },  
 
 ...
}

I have tried我试过了

new_dict = sorted(dict.items(), key=lambda x: x['Index'])

but Python objects to the str as the slice.但是 Python 对象以 str 作为切片。

Apart from the clunky method of iterating through and appending each item to a new dictionary what is the recommended method please?除了迭代每个项目并将其附加到新字典的笨拙方法之外,推荐的方法是什么?

Python dict is a hashed associative container, it cannot be sorted. Python dict 是一个散列关联容器,它无法排序。

Python 3 dict is insertion-ordered, so if you sort a copy of items collections of the original dictionary and comprehend it back into a dict it will be in the order you need. Python 3 dict 是按插入顺序排列的,因此如果您对原始字典的 items 集合的副本进行排序并将其理解为 dict,它将按照您需要的顺序排列。

x = {
    'Name2': {'value1': 5.0, 'value2': 0.1, 'Index': 1},
    'Name1': {'value1': 3.0, 'value2': 1.4, 'Index': 2}
}

y = {k: v for k, v in sorted(x.items(), key=lambda item: item[1]['Index'])}

Also, have you seen OrderedDict ?另外,你看过OrderedDict吗?

I'm assuming you meant:我假设你的意思是:

{'Name1' : {'value1': 3.0, 'value2': 1.4, 'Index': 2 },  
 'Name2' : {'value1': 5.0, 'value2': 0.1, 'Index': 1 },  
 ...
}

dict.items() iterates over pairs of keys and values, so in your lambda expression, x is not a dictionary like {'value1': ...} , but a tuple like ('Name2', {'value1': ...}) . dict.items()迭代键和值,因此在您的lambda表达式中, x不是像{'value1': ...}这样的字典,而是像('Name2', {'value1': ...}) .

You can change lambda x: x['Index'] to lambda x: x[1]['Index'] (ie, first get the second item of the tuple (which should now be the nested dictionary), then get the 'Index' value in that dictionary.您可以将lambda x: x['Index']更改为lambda x: x[1]['Index'] (即,首先获取元组的第二项(现在应该是嵌套字典),然后获取'Index'该字典中的'Index'值。

Next, sorted() will give you a list of key, value pairs (which may be appropriate).接下来, sorted()将为您提供一个键值对列表(这可能是合适的)。 If you really want a dictionary, you can change sorted(...) to dict(sorted(...)) , with two caveats:如果你真的想要一本字典,你可以将sorted(...)更改为dict(sorted(...)) ,但有两个警告:

  • In older Python versions this will lose the sorting again (see here ).在较旧的 Python 版本中,这将再次丢失排序(请参阅此处)。
  • Don't use dict as a variable name, otherwise you will shadow the built-in dict constructor and will get a type error "object is not callable".不要使用dict作为变量名,否则你会隐藏内置的dict构造函数,并且会得到一个类型错误“对象不可调用”。

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

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