6

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.

2 Answers 2

9

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).

Sign up to request clarification or add additional context in comments.

Comments

5

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(): 

1 Comment

@user3243366 Yes it does works see class collections.OrderedDict([items])¶ Return an instance of a dict subclass, supporting the usual dict methods.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.