用python从列表中制作字典 [英] Make dictionary from list with python

查看:26
本文介绍了用python从列表中制作字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将列表转换为字典,如下所示.奇数元素有键,偶数元素有值.

I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.

x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'}

def set(self, val_): 
    i = 0 
    for val in val_: 
        if i == 0: 
            i = 1 
            key = val 
        else: 
            i = 0 
            self.dict[key] = val 

获得相同结果的更好方法?

A better way to get the same results?

i = iter(k)
print dict(zip(i,i))

似乎在工作

推荐答案

dict(x[i:i+2] for i in range(0, len(x), 2))

这篇关于用python从列表中制作字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆