如何反转 python 字典中键的顺序?

发布于 2024-10-26 14:55:18 字数 230 浏览 2 评论 0原文

这是我的代码:

a = {0:'000000',1:'11111',3:'333333',4:'444444'}

for i in a:
    print i

它显示:

0
1
3
4

但我希望它显示:

4
3
1
0

那么,我能做什么?

This is my code :

a = {0:'000000',1:'11111',3:'333333',4:'444444'}

for i in a:
    print i

it shows:

0
1
3
4

but I want it to show:

4
3
1
0

so, what can I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

迎风吟唱 2024-11-02 14:55:18

注意:这个答案仅适用于 Python << 3.7.从 3.7 开始,字典是按顺序插入的(CPython 3.6 作为实现细节)。


键的迭代顺序是任意的。它们按顺序排列只是巧合。

>>> a = {0:'000000',1:'11111',3:'333333',4:'444444'}
>>> a.keys()
[0, 1, 3, 4]
>>> sorted(a.keys())
[0, 1, 3, 4]
>>> reversed(sorted(a.keys()))
<listreverseiterator object at 0x02B0DB70>
>>> list(reversed(sorted(a.keys())))
[4, 3, 1, 0]

Note: this answer is only true for Python < 3.7. Dicts are insertion ordered starting in 3.7 (and CPython 3.6 as an implementation detail).


The order keys are iterated in is arbitrary. It was only a coincidence that they were in sorted order.

>>> a = {0:'000000',1:'11111',3:'333333',4:'444444'}
>>> a.keys()
[0, 1, 3, 4]
>>> sorted(a.keys())
[0, 1, 3, 4]
>>> reversed(sorted(a.keys()))
<listreverseiterator object at 0x02B0DB70>
>>> list(reversed(sorted(a.keys())))
[4, 3, 1, 0]
奢欲 2024-11-02 14:55:18

Python 3.7 开始,字典保留顺序,这意味着您现在可以执行此操作:

my_dict = {'a': 1, 'c': 3, 'b': 2}

for k in reversed(list(my_dict.keys())):
    print(k)

输出:

b
c
a

Python 3.8 开始,内置函数 reversed() 也接受字典。

这是如何使用它进行迭代的示例:

my_dict = {'a': 1, 'c': 3, 'b': 2}

for k in reversed(my_dict):
    print(k)

这是如何用反向字典替换字典的示例:

my_dict = dict(reversed(my_dict.items()))

Since Python 3.7, dicts preserve order, which means you can do this now:

my_dict = {'a': 1, 'c': 3, 'b': 2}

for k in reversed(list(my_dict.keys())):
    print(k)

Output:

b
c
a

Since Python 3.8, the built-in function reversed() accepts dicts as well.

Here's an example of how you can use it to iterate:

my_dict = {'a': 1, 'c': 3, 'b': 2}

for k in reversed(my_dict):
    print(k)

Here's an example of how you can replace your dict with a reversed dict:

my_dict = dict(reversed(my_dict.items()))
森林迷了鹿 2024-11-02 14:55:18

字典是无序的,所以你不能颠倒它们。电流输出的顺序是任意的。

也就是说,您当然可以对键进行排序:

for i in sorted(a.keys(), reverse=True):
    print a[i];

但这会给您排序键的相反顺序,不一定是键添加方式的相反顺序。即如果你的字典是:它不会给你 1 0 3

a = {3:'3', 0:'0', 1:'1'}

Dictionaries are unordered so you cannot reverse them. The order of the current output is arbitrary.

That said, you can order the keys of course:

for i in sorted(a.keys(), reverse=True):
    print a[i];

but this gives you the reverse order of the sorted keys, not necessarily the reverse order of the keys how they have been added. I.e. it won't give you 1 0 3 if your dictionary was:

a = {3:'3', 0:'0', 1:'1'}
若有似无的小暗淡 2024-11-02 14:55:18

尝试:

for i in sorted(a.keys(), reverse=True):
    print i

Try:

for i in sorted(a.keys(), reverse=True):
    print i
终遇你 2024-11-02 14:55:18

Python dict 在 2.x 中没有排序。但是 3.1 中有一个有序的 dict 实现。

Python dict is not ordered in 2.x. But there's an ordered dict implementation in 3.1.

木森分化 2024-11-02 14:55:18

Python 字典没有任何与之关联的“顺序”。字典打印相同的顺序只是一个“巧合”。无法保证字典中的项目按任何顺序出现。

如果您想处理排序,则需要将字典转换为列表。

a = list(a) # keys in list
a = a.keys() # keys in list
a = a.values() # values in list
a = a.items() # tuples of (key,value) in list

现在,您可以正常对列表进行排序,例如,a.sort(),也可以反转它,例如,a.reverse()

Python dictionaries don't have any 'order' associated with them. It's merely a 'coincidence' that the dict is printing the same order. There are no guarantees that items in a dictionary with come out in any order.

If you want to deal with ordering you'll need to convert the dictionary to a list.

a = list(a) # keys in list
a = a.keys() # keys in list
a = a.values() # values in list
a = a.items() # tuples of (key,value) in list

Now you can sort the list as normal, e.g., a.sort() and reverse it as well, e.g., a.reverse()

私野 2024-11-02 14:55:18

在我使用的 Python 3.6 中,我借助函数更新颠倒了键及其各自值的顺序。

original_dict={'A':0,'C':2,'B':1}
new_dict={}
for k,v in original_dict.items():
    dict_element={k:v}
    dict_element.update(new_dict)
    new_dict=dict_element

print(new_dict)

它应该打印出来:

{'B':1,'C':2,'A':0}

我的 2 分。

In Python 3.6, which I am using, I reversed the order of keys with their respective values with the help of function update.

original_dict={'A':0,'C':2,'B':1}
new_dict={}
for k,v in original_dict.items():
    dict_element={k:v}
    dict_element.update(new_dict)
    new_dict=dict_element

print(new_dict)

It should print out:

{'B':1,'C':2,'A':0}

My 2 ¢.

疑心病 2024-11-02 14:55:18

如果您想保留插入顺序而不是字母顺序,那么您可以使用:

dict(list(your_dict.keys())[::-1])

或者对于整个字典:

<代码>dict(列表(your_dict.items())[::-1])

If you want to preserve the insertion order and not the alphabetical ordering, then you can use:

dict(list(your_dict.keys())[::-1])

Or for the whole dictionary:

dict(list(your_dict.items())[::-1])

关于从前 2024-11-02 14:55:18

如果你有这样的字典

{'faisal2': 2, 'umair': 2, 'fais': 1, 'umair2': 1, 'trending': 2, 'apple': 2, 'orange': 2}

并且你想对字典进行反向排序,你可以使用:

dict(sorted(counts.items(), key=lambda item: item[1],reverse=True))

输出将是:

{'faisal2': 2, 'umair': 2, 'trending': 2, 'apple': 2, 'orange': 2, 'fais': 1, 'umair2': 1}

If you have a dictionary like this

{'faisal2': 2, 'umair': 2, 'fais': 1, 'umair2': 1, 'trending': 2, 'apple': 2, 'orange': 2}

and you want to reverse sort dictionary you can use:

dict(sorted(counts.items(), key=lambda item: item[1],reverse=True))

output will be:

{'faisal2': 2, 'umair': 2, 'trending': 2, 'apple': 2, 'orange': 2, 'fais': 1, 'umair2': 1}
薄荷梦 2024-11-02 14:55:18
for i in reversed(sorted(a.keys())):
    print i
for i in reversed(sorted(a.keys())):
    print i
⊕婉儿 2024-11-02 14:55:18

只要尝试一下,

输入: a = {0:'000000',1:'11111',3:'333333',4:'444444'}

[x 代表已排序的 x(a.keys(), reverse=True)]

输出: [4, 3, 1, 0]

just try,

INPUT: a = {0:'000000',1:'11111',3:'333333',4:'444444'}

[x for x in sorted(a.keys(), reverse=True)]

OUTPUT: [4, 3, 1, 0]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文