Вопрос

I worked to access the item in ordered dictionary. d is the ordered dictionary:

print d.items()

Here the output is a pair. I want to access the key and value in this pair.

Это было полезно?

Решение

You can unpack the key, value (a tuple) as below:

for key, value in d.items():
    print (key)
    print (value)

This works both on python 2 and 3.

From docs:

Return a new view of the dictionary’s items ((key, value) pairs).

Другие советы

Each "pair" in d.items() is a tuple (ordered, immutable sequence) (key, value). You can "unpack" the values in each tuple into separate names, for example in a for loop:

for key, value in d.items():
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top