Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch the key/value pair of a dictionary only containing one item?

Let's say I have dict. I don't know the key/value inside. How do I get this key and the value without doing a for loop (there is only one item in the dict).

You might wonder why I am using a dictionary in that case. I have dictionaries all over my API and I don't want the user to be lost. It's only a matter of consistency. Otherwise, I would have used a list and indexes.

like image 895
user1720740 Avatar asked Mar 12 '13 16:03

user1720740


1 Answers

Use the proper data type for the job. Your goal should be to have workable code, not that you use the same data type all over the place.

If your dictionary only contains one key and one value, you can get either with indexing:

key = list(d)[0]
value = list(d.values())[0]

or to get both:

key, value = list(d.items())[0]

The list calls are needed because in Python 3, .keys(), .values() and .items() return dict views, not lists.

Another option is to use sequence unpacking:

key, = d
value, = d.values()

or for both at the same time:

(key, value), = d.items()
like image 184
Martijn Pieters Avatar answered Oct 13 '22 10:10

Martijn Pieters