python字典中循环(for循环)的顺序是什么? [英] what is the order of looping (for loop) in python dictionary
问题描述
我对从下面得到的输出有点困惑。
我不明白执行循环的顺序。
domains = {de:Germany sk:斯洛伐克,hu:匈牙利,
us:美国,否:挪威}
域:
打印键
这里的输出是
sk
de
no
us
hu
但不是
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ hu
no
同样,这里
num = {1:one,4:two,23:three,10:four}
for key in num:
print key
output is
1
10
4
23
但不是
pre $ 1
$ $ $ $ $ 23
10
感谢您的帮助
键入排序(域):
打印键
会产生
de
hu
no
sk
us
<如果你想要基于值进行排序,你可以使用像 sorted(domains.items(),key = lambda(k,v):(v,k))
。
Possible Duplicate:
Why is python ordering my dictionary like so?
I am a bit confused with the output I get from the following. I do not understand the order of the loop that is executed.
domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
"us": "United States", "no": "Norway" }
for key in domains:
print key
Output here is
sk
de
no
us
hu
but not
de
sk
hu
us
no
similarly, here
num = {1:"one",4:"two",23:"three",10:"four"}
for key in num:
print key
output is
1
10
4
23
but not
1
4
23
10
Thanks for helping
Python dictionaries don't have an order. However, you can specify an order by using the sorted(domains)
function. By default, it sorts using the key.
for key in sorted(domains):
print key
will produce
de
hu
no
sk
us
If you want to order based on values, you can use something like sorted(domains.items(), key = lambda(k, v): (v, k))
.
这篇关于python字典中循环(for循环)的顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!