>>> d = {'a':1, 'b':2, 'c':22, 'ap':'>'}
>>> for i in d: # ключи
... print(i)
...
a
ap
c
b
>>> for i in d: # ключи
... print(d[i]) # но по ключам можно получить значения
...
1
>
22
2
>>> for i in d.keys(): # Ключи, здесь не актуально, но может использоваться...
... print(i) # ...для получения всех ключей в выражении
...
a
ap
c
b
>>> tuple(d.keys()) # Например (см. пояснение выше)
('a', 'ap', 'c', 'b')
>>> for i in d.values(): # Значения
... print(i)
...
1
>
22
2
>>> for i in d.items(): # Кортежи ключей со значениями
... print(i)
...
('a', 1)
('ap', '>')
('c', 22)
('b', 2)
>>> for i,j in d.items():
... print('%s=%s' % i,j)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: not enough arguments for format string
>>> for i,j in d.items():
... print('%s=%s' % (i,j))
...
a=1
ap=>
c=22
b=2
>>> d.keys()
dict_keys(['a', 'ap', 'c', 'b'])
>>> d.values()
dict_values([1, '>', 22, 2])
>>> d.items()
dict_items([('a', 1), ('ap', '>'), ('c', 22), ('b', 2)])
>>> type(d.keys()), type(d.values()), type(d.items())
(<class 'dict_keys'>, <class 'dict_values'>, <class 'dict_items'>)
В отличие от Python3 в Python2 методы keys(), values() и items() возвращают не объекты классов dict_keys, dict_values и dict_items, а списки:
>>> d.keys()
['a', 'ap', 'c', 'b']
>>> d.values()
[1, '>', 22, 2]
>>> d.items()
[('a', 1), ('ap', '>'), ('c', 22), ('b', 2)]
>>> type(d.keys()), type(d.values()), type(d.items())
(<type 'list'>, <type 'list'>, <type 'list'>)