How to get a key / value pair of a dictionary containing only one element?

Let's say I dictated. I do not know the key / value inside. How to get this key and value without executing a for loop (there is only one element in the file).

You may wonder why I use the dictionary in this case. I have dictionaries throughout the API, and I do not want the user to be lost. This is only a matter of consistency. Otherwise, I would use a list and indexes.

+4
source share
4 answers

Use the correct data type for the job. Your goal should be to have workable code, and not that you use the same data type everywhere.

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

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

or get both:

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

list calls are needed because in Python 3, .keys() , .values() and .items() return dict requests, 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() 
+9
source

Just enter the first element in the dictionary using an iterator

 >>> d = {"foo":"bar"} >>> k, v = next(iter(d.items())) >>> k 'foo' >>> v 'bar' 
+6
source

You can do it:

 >>> d={1:'one'} >>> k=list(d)[0] >>> v=d[k] 

Works on Python 2 or 3

+1
source

d.popitem() will give you the key, a tuple of value.

0
source

Source: https://habr.com/ru/post/1468753/


All Articles