python中2个列表组合生成对应的字典

1、构建字典的 2 个列表相同

>>> a = [1,2,3,4]
>>> b = ['ab','ac','ad']
>>> dict(zip(a,b))
{1: 'ab', 2: 'ac', 3: 'ad'}
>>>

2、构建字典的 2 个列表不同(key比value多)

>>> a = [1,2,3,4]
>>> c = ['aa','ss']
>>> dict(zip(a,c))
{1: 'aa', 2: 'ss'}
>>>

3、构建字典的 2 个列表不同(key比value少)

>>> a = [1,2,3,4]
>>> d = ['fa','fb','fc','fd','fe']
>>> dict(zip(a,d))
{1: 'fa', 2: 'fb', 3: 'fc', 4: 'fd'}
>>>

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

>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]

>>>dict(list)

{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

或者这样:

>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]

>>>new_dict = {}

>>> for i in new_list:

...   new_dict[i[0]] = i[1]                #字典赋值,左边为key,右边为value

...

>>> new_dict

{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/87808233