开发者

How to get value on a certain index, in a python list?

I have a list which 开发者_如何学JAVAlooks something like this

List = [q1,a1,q2,a2,q3,a3]

I need the final code to be something like this

dictionary = {q1:a1,q2:a2,q3:a3}

if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it?


Python dictionaries can be constructed using the dict class, given an iterable containing tuples. We can use this in conjunction with the range builtin to produce a collection of tuples as in (every-odd-item, every-even-item), and pass it to dict, such that the values organize themselves into key/value pairs in the final result:

dictionary = dict([(List[i], List[i+1]) for i in range(0, len(List), 2)])


Using extended slice notation:

dictionary = dict(zip(List[0::2], List[1::2]))


The range-based answer is simpler, but there's another approach possible using the itertools package:

from itertools import izip
dictionary = dict(izip(*[iter(List)] * 2))

Breaking this down (edit: tested this time):

# Create instance of iterator wrapped around List
# which will consume items one at a time when called.
iter(List)

# Put reference to iterator into list and duplicate it so
# there are two references to the *same* iterator.
[iter(List)] * 2 

# Pass each item in the list as a separate argument to the
# izip() function.  This uses the special * syntax that takes
# a sequence and spreads it across a number of positional arguments.
izip(* [iter(List)] * 2)

# Use regular dict() constructor, same as in the answer by zzzeeek
dict(izip(* [iter(List)] * 2))

Edit: much thanks to Chris Lutz' sharp eyes for the double correction.


d = {}
for i in range(0, len(List), 2):
    d[List[i]] = List[i+1]


You've mentioned in the comments that you have duplicate entries. We can work with this. Take your favorite method of generating the list of tuples, and expand it into a for loop:

from itertools import izip

dictionary = {}
for k, v in izip(List[::2], List[1::2]):
    if k not in dictionary:
        dictionary[k] = set()
    dictionary[k].add(v)

Or we could use collections.defaultdict so we don't have to check if a key is already initialized:

from itertools import izip
from collections import defaultdict

dictionary = defaultdict(set)
for k, v in izip(List[::2], List[1::2]):
    dictionary[k].add(v)

We'll end with a dictionary where all the keys are sets, and the sets contain the values. This still may not be appropriate, because sets, like dictionaries, cannot hold duplicates, so if you need a single key to hold two of the same value, you'll need to change it to a tuple or a list. But this should get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜