Reputation: 773
If I have some dictionary like:
d = {'keyname': ['foo', 'bar']}
and I don't know the key name how I would unpack this dict in two variables?
This doesn't work:
k,v = d
I could iterate over this dict like:
for k, v in d.items():
# k and v are now available
But I think this is not the "pythonic" way enough
How can I do this without using a for-loop?
"d"
can always have only ONE key:val
pair.
Upvotes: 0
Views: 123
Reputation: 3059
d = {'keyname': ['foo', 'bar']}
for k in d.keys(): key = k
val = d[k]
print key, val
Upvotes: 0
Reputation: 5275
In Python 2.x
If your dictionary
is always going to be of length 1 then this can be one possible solution:
>>> d = {'keyname': ['foo', 'bar']}
>>> k, v = d.keys()[0], d.values()[0]
>>> k
'keyname'
>>> v
['foo', 'bar']
For both Python 2.x and 3.x
Using .items()
>>> k, v = d.items()[0]
>>> k
'keyname'
>>> v
['foo', 'bar']
For python 3.x
>>> d = {'keyname': ['foo', 'bar']}
>>> k, v = tuple(d.keys())[0], tuple(d.values())[0]
>>> k
'keyname'
>>> v
['foo', 'bar']
Upvotes: 2
Reputation:
You can use iterable unpacking:
>>> d = {'keyname': ['foo', 'bar']}
>>> [(k, v)] = d.items()
>>> k
'keyname'
>>> v
['foo', 'bar']
>>>
This works in both Python 2.x and Python 3.x.
Note however that if you are using Python 2.x, it would be slightly more efficient to use d.iteritems()
instead of d.items()
:
>>> from timeit import timeit
>>> d = {'keyname': ['foo', 'bar']}
>>> timeit('[(k, v)] = d.items()', 'from __main__ import d')
0.786108849029695
>>> timeit('[(k, v)] = d.iteritems()', 'from __main__ import d')
0.6730112346680928
>>>
This is because iteritems
returns an iterator while items
builds an unnecessary list.
Upvotes: 3