Python中把列表转换为字典

有以下几个方法:

1、 现在有两个列表,list1 = ['key1','key2','key3']list2 = ['1','2','3'],把他们转为这样的字典:{'key1':'1','key2':'2','key3':'3'}

1
2
3
4
list1 = ['key1','key2','key3']
list2 = ['1','2','3']
print dict(zip(list1, list2))
# {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

2、 将嵌套列表转为字典,有两种方法

1
2
3
4
5
6
new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
new_dict = {}
for i in new_list:
new_dict[i[0]] = i[1]
print new_dict()
#{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
1
2
3
new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
print dict(new_list)
#{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

3、 list1 = [k1 : {key1 : value1, key2 : value3}] 转变成 list2 = [k1: [ {key1 : value1}, {key2 : value2}] ]

1
2
3
4
5
6
7
for k, v in list1.items:
sm = {}
sm[k] = v
list2.append(sm)
print list2
# [k1: [ {key1 : value1}, {key2 : value2}] ]

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×