question about list of dictionary items

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Thu Jul 22 02:25:08 EDT 2004


Joe Wong wrote:

> HI,
> 
>  I have a list contains dictionary items, for example:
> 
> l = [{1:'apple'}, {2:'Orange'}, {133:'lemon'}]
> 
> What is the quickest way to extact all the 'keys' from the list?

First of all, that's a highly unusual data structure - do *all* of your
dictionaries in the list contain only a single element?. I'm guessing
that you want a list of pairs of (key, value). In which case, you should
use tuples i.e.

    l = [(1, 'apple'), (2, 'Orange'), (133, 'lemon')]

The other alternative that makes sense to me is to use an actual
dictionary:

    d = {
        1: 'apple',
        2: 'Orange',
        3: 'lemon',
    }

In each case, it's simple to convert one to another - dict(iterable)
where iterable consists of tuples of (key, value) creates a dictionary.
dict.items() or dict.iteritems() returns an iterator of tuples of (key,
value).

Secondly, what do you mean by "fastest"? Do you mean fastest/simplest to
code? Or do you mean the fastest to actually run? If the latter, I'd
suggest you forget it - unless your dataset is *very* large, it won't
make any perceptible difference.

Now, to get the keys out of your specific example, the simplest way is
probably to create a new (empty) list, iterate over the original list
and extend the new list with the keys of each element until you're done.
The code is *very* short, but I'll let you work it out yourself.

Tim Delaney



More information about the Python-list mailing list