从词典python中选择一个键

时间:2011-10-18 17:15:33

标签: python dictionary

通过字典从循环中挑选键吗?

例如,假设我有以下词典:{'hello':'world', 'hi':'there'}。有没有办法让for遍历字典并打印hello, hi

在类似的说明中有一种方法可以说myDictionary.key[1]并且会返回hi吗?

5 个答案:

答案 0 :(得分:4)

您可以使用for循环迭代dict的键:

>>> for key in yourdict:
>>>    print(key)
hi
hello

如果您希望将它们作为逗号分隔字符串,则可以使用', '.join

>>> print(', '.join(yourdict))
hi, hello

  

在类似的说明中有一种方法可以说myDictionary.key 1并且会返回hi

没有。字典中的键没有任何特定的顺序。迭代它们时看到的顺序可能与将它们插入字典中的顺序不同,并且在添加或删除项目时,顺序理论上也会发生变化。

如果您需要有序的收藏品,可能需要考虑使用其他类型,例如listOrderedDict

答案 1 :(得分:4)

您可以使用.keys()方法:

for key in myDictionary.keys():
   print key

您也可以使用.items()同时迭代两者:

for key, value in myDictionary.items():
   print key, value

答案 2 :(得分:1)

Python 2中的

dict.iterkeys,Python 3中的dict.keys

d = { 'hello': 'world', 'hi': 'there' }
for key in d.iterkeys():
    print key

答案 3 :(得分:1)

使用字典名称作为序列产生所有键:

>>> d={'hello':'world', 'hi':'there'}
>>> list(d)
['hi', 'hello']

所以list({'hello':'world', 'hi':'there'})[1]生成键列表的元素1。

然而,这是有限的用途,因为字典是无序的。它们的顺序可能与插入顺序不同:

>>> d={'a': 'ahh', 'b': 'baa', 'c': 'coconut'}
>>> d
{'a': 'ahh', 'c': 'coconut', 'b': 'baa'}

您可以对dict键的排序列表的1个元素执行sorted(list({'hello':'world', 'hi':'there'}))[1]。在这种情况下产生'hi'。虽然不是最具可读性或效率......

如果您想要排序的订单,请查看OrderedDict

或者只是排序到列表中:

>>> d={'a': 'ahh', 'b': 'baa', 'c': 'coconut'}
>>> l=[(k,v) for k, v in d.items()]
>>> l.sort()
>>> l[1]
('b', 'baa')
>>> l[1][0]
'b'

如果您想按值而不是按键排序,则可以将(k,v)反转为(v,k)

答案 4 :(得分:0)

听起来像钥匙列表可以满足您的需求:

>>> d = { 'hello': 'world', 'hi': 'there' }
>>> keys = list(d)
>>> keys
['hi', 'hello']
>>> from random import choice
>>> choice(keys)
'hi'