Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract dictionary single key-value pair in variables

People also ask

How do you separate a key from a value in a dictionary?

Creating a Dictionary To do that you separate the key-value pairs by a colon(“:”). The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be changed at runtime such as int, string, tuple, etc. The values can be of any type.


Add another level, with a tuple (just the comma):

(k, v), = d.items()

or with a list:

[(k, v)] = d.items()

or pick out the first element:

k, v = d.items()[0]

The first two have the added advantage that they throw an exception if your dictionary has more than one key, and both work on Python 3 while the latter would have to be spelled as k, v = next(iter(d.items())) to work.

Demo:

>>> d = {'foo': 'bar'}
>>> (k, v), = d.items()
>>> k, v
('foo', 'bar')
>>> [(k, v)] = d.items()
>>> k, v
('foo', 'bar')
>>> k, v = d.items()[0]
>>> k, v
('foo', 'bar')
>>> k, v = next(iter(d.items()))  # Python 2 & 3 compatible
>>> k, v
('foo', 'bar')

items() returns a list of tuples so:

(k,v) = d.items()[0]

>>> d = {"a":1}
>>> [(k, v)] = d.items()
>>> k
'a'
>>> v
1

Or using next, iter:

>>> k, v = next(iter(d.items()))
>>> k
'a'
>>> v
1
>>>

d = {"a": 1}

you can do

k, v = d.keys()[0], d.values()[0]

d.keys() will actually return list of all keys and d.values() return list of all values, since you have a single key:value pair in d you will be accessing the first element in list of keys and values


This is best if you have many items in the dictionary, since it doesn't actually create a list but yields just one key-value pair.

k, v = next(d.iteritems())

Of course, if you have more than one item in the dictionary, there's no way to know which one you'll get out.