2

I keep trying to get a list of keys out of my dict by using dict.keys but it keeps giving me:

def reverse(PB = {'l': 3, 'y':1, 'u':2}): print(PB.keys())

prints:

dict_keys(['u', 'l', 'y'])

I've never had this issue before I have a python version beyond 2.7... any ideas?

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
Joe Crane
  • 47
  • 7

1 Answers1

5

Python 3 returns view objects:

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

You can convert them into a list (the Python 2 behavior) by passing them into list():

>>> d = {'l': 3, 'y':1, 'u':2}
>>> d.keys()
dict_keys(['y', 'l', 'u'])
>>> list(d.keys())
['y', 'l', 'u']

Also, be careful with passing mutable objects as default arguments:

>>> def reverse(PB={'l': 3, 'y':1, 'u':2}):
...     PB['l'] += 4
...     
...     print(PB)
... 
>>> reverse()
{'y': 1, 'l': 7, 'u': 2}
>>> reverse()
{'y': 1, 'l': 11, 'u': 2}
>>> reverse()
{'y': 1, 'l': 15, 'u': 2}

I'd default to None instead:

def reverse(PB=None):
    if PB is None:
        PB = {'l': 3, 'y':1, 'u':2}
Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496