循环遍历字典从中挑选键?
例如,假设我有以下字典:{'hello':'world', 'hi':'there'}
。有没有一种方法可以for
遍历字典并打印hello, hi
?
在类似的注释中,有没有一种方法可以说 myDictionary.key[1]
并且会返回 hi
?
最佳答案
您可以使用 for 循环遍历字典的键:
>>> for key in yourdict:
>>> print(key)
hi
hello
如果您希望它们作为逗号分隔的字符串,您可以使用 ', '.join
。
>>> print(', '.join(yourdict))
hi, hello
on a similar note is there a way to say myDictionary.key1 and that will return hi
没有。字典中的键没有任何特定的顺序。您在迭代它们时看到的顺序可能与您将它们插入字典的顺序不同,理论上,当您添加或删除项目时,顺序可能会发生变化。
如果您需要有序集合,您可能需要考虑使用另一种类型,例如 list
或 OrderedDict
关于python - 从字典 python 中选择一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7811130/