Python dict.fromkeys按与列表相反的顺序返回字典
我正在将列表中的所有项添加到字典中,作为等于none的键Python dict.fromkeys按与列表相反的顺序返回字典,python,dictionary,Python,Dictionary,我正在将列表中的所有项添加到字典中,作为等于none的键 template_vars = headers[1:] kwargs = dict.fromkeys(template_vars) 当我在终端中打印两个变量的值时,它们如下所示 {'Type': 'Nauman Ahmad', 'Name': 'Cyborg'} ['Name', 'Type'] 命令的顺序颠倒了吗?在Python中,Dict从不排序,它实际上以随机顺序存储键、值对,并使用键获取它们。如果要保持顺序,请改用。在Pyth
template_vars = headers[1:]
kwargs = dict.fromkeys(template_vars)
当我在终端中打印两个变量的值时,它们如下所示
{'Type': 'Nauman Ahmad', 'Name': 'Cyborg'}
['Name', 'Type']
命令的顺序颠倒了吗?在Python中,Dict从不排序,它实际上以随机顺序存储键、值对,并使用键获取它们。如果要保持顺序,请改用。在Python中,Dict从不排序,它实际上以随机顺序存储键、值对,并使用键获取。如果要保持顺序,请改用。字典是无序的。如果订单很重要,请使用OrderedICT:
from collections import OrderedDict
kwargs=OrderedDict((k, None) for k in template_vars)
字典是无序的。如果订单很重要,请使用OrderedICT:
from collections import OrderedDict
kwargs=OrderedDict((k, None) for k in template_vars)
请注意,您可以将
fromkeys
与OrderedICT
一起使用。请注意,您可以将fromkeys
与OrderedICT