Reputation: 38940
go through a dictionary picking keys from it in a loop?
For example lets say I have the following dictionary: {'hello':'world', 'hi':'there'}
. Is there a way to for
loop through the dictionary and print hello, hi
?
on a similar note is there a way to say myDictionary.key[1]
and that will return hi
?
Upvotes: 1
Views: 19724
Reputation: 39893
You can use the .keys()
method:
for key in myDictionary.keys():
print(key)
You can also use .items()
to iterate through both at the same time:
for key, value in myDictionary.items():
print(key, value)
Upvotes: 5
Reputation:
Using the dictionary name as a sequence produces all the keys:
>>> d={'hello':'world', 'hi':'there'}
>>> list(d)
['hi', 'hello']
so list({'hello':'world', 'hi':'there'})[1]
produces element 1 of the list of keys.
This is of limited use, however, because dictionaries are unordered. And their order may be different than the order of insertion:
>>> d={'a': 'ahh', 'b': 'baa', 'c': 'coconut'}
>>> d
{'a': 'ahh', 'c': 'coconut', 'b': 'baa'}
You can do sorted(list({'hello':'world', 'hi':'there'}))[1]
for the 1 element of a sorted list of the keys of your dict. That produces 'hi' in this case. Not the most readable or efficient though...
You should look at OrderedDict if you want a sorted order.
Or just sort into a list:
>>> 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'
You can reverse (k,v)
to (v,k)
if you want to sort by value instead of by key.
Upvotes: 2
Reputation: 226306
Sounds like a list of keys would meet your needs:
>>> d = { 'hello': 'world', 'hi': 'there' }
>>> keys = list(d)
>>> keys
['hi', 'hello']
>>> from random import choice
>>> choice(keys)
'hi'
Upvotes: 0
Reputation: 838196
You can iterate over the keys of a dict with a for loop:
>>> for key in yourdict:
>>> print(key)
hi
hello
If you want them as a comma separated string you can use ', '.join
.
>>> print(', '.join(yourdict))
hi, hello
on a similar note is there a way to say myDictionary.key1 and that will return hi
No. The keys in a dictionary are not in any particular order. The order that you see when you iterate over them may not be the same as the order you inserted them into the dictionary, and also the order could in theory change when you add or remove items.
if you need an ordered collection you might want to consider using another type such as a list
, or an OrderedDict
Upvotes: 4
Reputation: 129764
dict.iterkeys
in Python 2, dict.keys
in Python 3.
d = { 'hello': 'world', 'hi': 'there' }
for key in d.iterkeys():
print key
Upvotes: 1