Dictionary 列举字典中的键?
我有一本字典Dictionary 列举字典中的键?,dictionary,python-2.7,Dictionary,Python 2.7,我有一本字典 Dict = {'ALice':1, 'in':2, 'Wonderland':3} 我可以找到返回键值的方法,但无法返回键名 我希望Python一步一步地返回字典键名(for loop),例如: Alice in Wonderland 您可以使用.keys(): 或者只是反复浏览字典: for key in your_dict: print key 请注意,字典不是按顺序排列的。生成的关键点将以某种随机顺序出现: ['Wonderland', 'ALice', 'in'
Dict = {'ALice':1, 'in':2, 'Wonderland':3}
我可以找到返回键值的方法,但无法返回键名
我希望Python一步一步地返回字典键名(for loop),例如:
Alice
in
Wonderland
您可以使用.keys()
:
或者只是反复浏览字典:
for key in your_dict:
print key
请注意,字典不是按顺序排列的。生成的关键点将以某种随机顺序出现:
['Wonderland', 'ALice', 'in']
如果您关心顺序,解决方案是使用列表,这些列表是按顺序排列的: 现在,您可以获得所需的结果:
>>> sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
>>>
>>> for key, value in sort_of_dict:
... print key
...
ALice
in
Wonderland
dict有一个keys()方法
Dict.keys()将返回键列表,或使用迭代器方法iterkeys()
打印:{'alpha':0,'beta':1,'zeta':2}
编辑:如果您希望对dict进行排序,请使用ordereddict。我可能会尝试将其转换为适当的值-键对列表,然后在此示例中根据值进行排序,然后进行迭代。(记住字典里的键是不排序的。)排序对我来说不是问题。我不需要特定的顺序。我只是想在SQL数据库中输入密钥名称。
对于您的目录中的密钥():
可以简化为对于您的目录中的密钥:
@NolenRoyalty:谢谢!不知道为什么我错过了。这不完全是问题的答案,但我投了更高的票,因为这是一个方便的把戏。
sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
for key, value in sort_of_dict:
print key
>>> sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]
>>>
>>> for key, value in sort_of_dict:
... print key
...
ALice
in
Wonderland
def enumdict(listed):
myDict = {}
for i, x in enumerate(listed):
myDict[x] = i
return myDict
indexes = ['alpha', 'beta', 'zeta']
print enumdict(indexes)