I'm creating the stable matching project in Python, and I'm trying to iterate over the keys of a dict
using iterkeys()
, but I'm getting the following error:
AttributeError: dict object has no attribute iterkeys
This is my dict:
preferred_rankings_men = {
'ryan': ['lizzy', 'sarah', 'zoey', 'daniella'],
'josh': ['sarah', 'lizzy', 'daniella', 'zoey'],
'blake': ['sarah', 'daniella', 'zoey', 'lizzy'],
'connor': ['lizzy', 'sarah', 'zoey', 'daniella']
}
And here is my function:
def init_free_men():
for man in preferred_rankings_men.iterkeys():
free_men.append(man)
dict.iterkeys()
method is deprecated in Python 3. The equivalent code would be:
for man in preferred_rankings_men:
.iterkeys()
is the old Python 2 method for getting an iterator over the keys. In Python 3, if you must use a method call, you'd use .keys()
which gets an iterable view of the dict
s keys. That said, the simplest solution is not to call a method at all; dict
s are already iterables of their keys, so:
def init_free_men():
for man in preferred_rankings_men:
free_men.append(man)
works efficiently on both Python 2 and Python 3, and can even be simplified further to:
def init_free_men():
free_men.extend(preferred_rankings_men)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With