python Two small ways to turn a list into a dictionary Summary of of
- 2021-07-06 11:06:28
- OfStack
1. Now there are two lists, list1 = ['key1', 'key2', 'key3'] and list2 = ['1', '2', '3']. Turn them into dictionaries like this: {'key1': '1', 'key2': '2', 'key3': '3'}
>>>list1 = ['key1','key2','key3']
>>>list2 = ['1','2','3']
>>>dict(zip(list1,list2))
{'key1':'1','key2':'2','key3':'3'}
2. There are two ways to turn nested lists into dictionaries.
>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
>>>dict(list)
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
Or this:
>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
>>>new_dict = {}
>>> for i in new_list:
... new_dict[i[0]] = i[1] # Dictionary assignment, left side is key On the right value
...
>>> new_dict
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}