简体   繁体   English

列表与键和值的字典

[英]List to dictionary with keys and values

I have a list (myarray) that looks something like this, 我有一个列表(myarray)看起来像这样,

[u 'item-01', 52, u 'item-02', 22, u 'item-03', 99, u 'item-04', 84]

I'm trying to convert this into a dictionary with keys and value. 我正在尝试将其转换为具有键和值的字典。

I've tried looping but doesn't give me the expected results, 我试过循环,但没有给我预期的结果,

mydict = {}
for k,v in myarray:
mydict[k] = v

Simple: Use zip and extended slicing. 简单:使用zip和扩展切片。

mydict = dict(zip(myarray[::2], myarray[1::2]))

The first extended slice makes a list of all even indices, the second of all odd, the zip pairs them up into tuple s, and the dict constructor can take an iterable of paired values and initialize using them as key/value pairs. 第一个扩展切片list了所有偶数索引,第二个是奇数, zip将它们组合成tuple ,而dict构造函数可以采用可迭代的配对值并使用它们作为键/值对进行初始化。

Note: Padraig's solution of using iter will work faster (and handle non-sequence iterables), though it is somewhat less intuitive (and not quite as succinct as written). 注意:Padraig使用iter的解决方案可以更快地工作(并处理非序列迭代),虽然它不太直观(并不像编写的那样简洁)。 Of course, it can be one-lined at the expense of becoming even less intuitive by using the behavior of list multiplication copying references (see Note 2 on the table of sequence operations; an example of another use for it is found in the itertools grouper recipe ): 当然,它可以通过使用list乘法复制引用的行为而牺牲变得更加直观(参见序列操作表中的注释2;在itertools grouper找到它的另一个用途的示例) 食谱 ):

mydict = dict(zip(*[iter(myarray)]*2))

You can combine iter and zip : 你可以结合iterzip

l = [u'item-01', 52, u'item-02', 22, u'item-03', 99, u'item-04', 84]

it = iter(l)

print(dict(zip(it, it)))
{u'item-04': 84, u'item-01': 52, u'item-03': 99, u'item-02': 22}

zip(it, it) creates pairs combining every two elements, calling dict on the result uses the first element of each tuple as the key and the second as the vale. zip(it, it)创建组合每两个元素的对,在结果上调用dict使用每个元组的第一个元素作为键,第二个元素作为vale。

In [16]: it = iter(l)

In [17]: l = list(zip(it,it))

In [18]: l
Out[18]: [('item-01', 52), ('item-02', 22), ('item-03', 99), ('item-04', 84)]

In [19]: dict(l)
Out[19]: {'item-01': 52, 'item-02': 22, 'item-03': 99, 'item-04': 84}

Using a for loop like your own code: 像你自己的代码一样使用for循环:

it = iter(l)
d = {}
for k, v in it:
    d[k] = v

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM