相关疑难解决方法(0)

字典:如何保持键/值与声明的顺序相同?

我有一个字典,我按特定顺序声明,并希望始终保持该顺序.键/值不能根据它们的值按顺序保存,我只是按照我声明的顺序想要它.

所以,如果我有字典:

d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}
Run Code Online (Sandbox Code Playgroud)

如果我查看它或迭代它,它是不是按顺序,有没有办法确保Python将保持我声明键/值的显式顺序?

python sorting dictionary

292
推荐指数
8
解决办法
30万
查看次数

为什么python会像这样订购我的字典?

这是我的字典

propertyList = {
    "id":           "int",
    "name":         "char(40)",

    "team":         "int",
    "realOwner":    "int",

    "x":            "int",
    "y":            "int",

    "description":  "char(255)",

    "port":         "bool",
    "secret":       "bool",
    "dead":         "bool",
    "nomadic":      "bool",

    "population":   "int",
    "slaves":       "int",
}
Run Code Online (Sandbox Code Playgroud)

但是当我用"\n".join(myDict)打印出来时,我得到了这个

name
nomadic
dead
port
realOwner
secret
slaves
team
y
x
population
id
description
Run Code Online (Sandbox Code Playgroud)

我知道字典是无序的,但每次出现都是一样的,我不知道为什么.

python dictionary

41
推荐指数
3
解决办法
4万
查看次数

for..in ..以随机顺序打印字典

我写了下面的代码,当这段代码执行时,输出就像

一个:33.75%

零:32.98%

二:33.27%

我的问题是,为什么不按顺序排列,我该怎么做?

import random 
a=0
dict = {"zero":0,"one":0,"two":0}
while a < 10000:
    a +=1
    b = random.randrange(0,3)
    if b == 0:
        dict["zero"] += 1
    elif b == 1:
        dict["one"] += 1
    elif b == 2:
        dict["two"] += 1
for item in dict:
    dict[item] /= 100
    dict[item] = str(dict[item])+"%"
    print(item + ":" + dict[item])  
Run Code Online (Sandbox Code Playgroud)

python

-3
推荐指数
1
解决办法
95
查看次数

标签 统计

python ×3

dictionary ×2

sorting ×1