python - 使用列表值作为字典键作为键值

标签 python python-3.x python-2.7

我正在创建一个使用列表值作为键的字典。现在我想以与列表值相同的顺序获取字典键。请在下面找到代码:

dict = {}

category_list = [u'Customer', u'Consumers', u'OpenERP Partners', u'Basic Partner', u'Retailers', u'Supplier']

for category in category_list:
    dict[category] = 0.0

print "dict--->", dict 

我得到的输出是:

dict--->{u'Customer': 0.0, u'Consumers': 0.0, u'Basic Partner': 0.0, u'Supplier': 0.0, u'Retailers': 0.0, u'OpenERP Partners': 0.0}

但我希望字典键的顺序与定义列表的顺序相同。即输出应该是这样的:

 dict--->{u'Customer': 0.0, u'Consumers': 0.0, u'OpenERP Partners': 0.0, u'Basic Partner': 0.0,  u'Retailers': 0.0, u'Supplier': 0.0,}

最佳答案

您需要使用 OrderedDict .例如:

>>> import collections
>>> d = collections.OrderedDict()
>>> category_list = [u'Customer', u'Consumers', u'OpenERP Partners', u'Basic Partner', u'Retailers', u'Supplier']
>>> for category in category_list:
...   d[category] = 0.0
... 
>>> print d
OrderedDict([(u'Customer', 0.0), (u'Consumers', 0.0), (u'OpenERP Partners', 0.0), (u'Basic Partner', 0.0), (u'Retailers', 0.0), (u'Supplier', 0.0)])

此外,dict 已经在 python 中用于引用 dict 类,因此您应该避免将其用作变量名。

关于python - 使用列表值作为字典键作为键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10578232/

相关文章:

python - 处理大量数据而无需等待 block 完成

python - Anaconda/Spyder突然崩溃并启动错误: Socket issue and/or ImportError

python-2.7 - 错误:- tensorboard: command not found .但是,在输入locatetensorboard时,我得到了位置

python - pprint 字典在多行

python - Snow Leopard 上的 PyObjc 和 Cocoa

python - 当将 imaplib 与 cx_Freeze 一起使用时,获取 "module ' imaplib' 没有属性 'IMAP4_SSL'

python:为什么os.makedirs会导致WindowsError?

python - 设置所有子图中刻度的大小

python - Docker容器启动后退出

python - OpenCV 的 label2rgb 实现