Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'dict' object has no attribute 'iterkeys'

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)
like image 878
John Rayburn Avatar asked Sep 17 '25 14:09

John Rayburn


2 Answers

dict.iterkeys() method is deprecated in Python 3. The equivalent code would be:

for man in preferred_rankings_men:
like image 136
Selcuk Avatar answered Sep 20 '25 03:09

Selcuk


.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 dicts keys. That said, the simplest solution is not to call a method at all; dicts 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)
like image 37
ShadowRanger Avatar answered Sep 20 '25 04:09

ShadowRanger