Reputation: 415
I have a list that contains several tuples, like:
[('a_key', 'a value'), ('another_key', 'another value')]
where the first tuple-values act as dictionary-keys. I'm now searching for a python-like way to access the key/value-pairs, like:
"mylist.a_key"
or "mylist['a_key']"
without iterating over the list. any ideas?
Upvotes: 4
Views: 4418
Reputation: 9469
If you're generating the list yourself, you might be able to create it as a dictionary at source (which allows for key, value pairs).
Otherwise, Van Gale's defaultdict is the way to go I would think.
Edit:
As mentioned in the comments, defaultdict is not required here unless you need to deal with corner cases like several values with the same key in your list. Still, if you can originally generate the "list" as a dictionary, you save yourself having to iterate back over it afterwards.
Upvotes: 3
Reputation: 95536
You can't do it without any iteration. You will either need iteration to convert it into a dict, at which point key access will become possible sans iteration, or you will need to iterate over it for each key access. Converting to a dict seems the better idea-- in the long run it is more efficient, but more importantly, it represents how you actually see this data structure-- as pairs of keys and values.
>>> x = [('a_key', 'a value'), ('another_key', 'another value')]
>>> y = dict(x)
>>> y['a_key']
'a value'
>>> y['another_key']
'another value'
Upvotes: 14