如何根据列表

时间:2016-06-03 20:40:33

标签: python sorting dictionary

我有一本字典:

my_dict = {
    'key1': [v1,v2,v3],
    'key2': [v1,v2,v3],
    'key3': [v1,v2,v3]
}

如何根据列表中的my_dict项对v3内的键进行排序。v3}是一个浮点值。

我的解决方案: 我创建了一个列表的嵌套列表,

new_list = [[Key1,v3],[key2,v3],[key3,v3]]

然后根据v3元素对该列表进行排序。 后来我使用了for循环:

for each in new_list:
     for i in my_dict:
        if each[0] == i:
           new_orderedDict[i] = my_dict[i]

这样我就可以使用有序字典获得排序键。

任何最佳方式?

1 个答案:

答案 0 :(得分:1)

首先,我必须指出,既然您是StackOverflow的新手,那么您需要尝试解决问题并展示您尝试过的内容。其次,Python中的 Ambient (since Linux 4.3): This is a set of capabilities that are preserved across an execve(2) of a program that is not privileged. The ambient capability set obeys the invariant that no capability can ever be ambient if it is not both permitted and inheritable. The ambient capability set can be directly modified using prctl(2). Ambient capabilities are automatically lowered if either of the corresponding permitted or inheritable capabilities is lowered. Executing a program that changes UID or GID due to the set- user-ID or set-group-ID bits or executing a program that has any file capabilities set will clear the ambient set. Ambient capabilities are added to the permitted set and assigned to the effective set when execve(2) is called. A child created via fork(2) inherits copies of its parent's capability sets. See below for a discussion of the treatment of capabilities during execve(2). Transformation of capabilities during execve() During an execve(2), the kernel calculates the new capabilities of the process using the following algorithm: P'(ambient) = (file is privileged) ? 0 : P(ambient) P'(permitted) = (P(inheritable) & F(inheritable)) | (F(permitted) & cap_bset) | P'(ambient) P'(effective) = F(effective) ? P'(permitted) : P'(ambient) P'(inheritable) = P(inheritable) [i.e., unchanged] where: P denotes the value of a thread capability set before the execve(2) P' denotes the value of a thread capability set after the execve(2) F denotes a file capability set cap_bset is the value of the capability bounding set (described below). A privileged file is one that has capabilities or has the set-user-ID or set-group-ID bit set. 不是真的有#34;顺序" - dict基本上只是一个哈希表。

但是,collections.OrderedDict()(与sorted()结合使用)可以达到您想要的效果:

  

返回一个dict子类的实例,支持通常的dict方法。 OrderedDict是一个dict,它记住了第一次插入键的顺序。如果新条目覆盖现有条目,则原始插入位置保持不变。删除一个条目并重新插入它将把它移到最后。

以下是一个例子:

dict