Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we access key and value in the ordereddict in python.?

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.

like image 837
user3243366 Avatar asked Jan 28 '14 08:01

user3243366


2 Answers

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

like image 66
Nabin Avatar answered Sep 18 '22 08:09

Nabin


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():
like image 24
jonrsharpe Avatar answered Sep 18 '22 08:09

jonrsharpe