list to dict code example
Example 1: list to dict python
my_list = ['Nagendra','Babu','Nitesh','Sathya']
my_dict = dict()
for index,value in enumerate(my_list):
my_dict[index] = value
print(my_dict)
{0: 'Nagendra', 1: 'Babu', 2: 'Nitesh', 3: 'Sathya'}
Example 2: convert list to dictionary using python
def Convert(lst):
res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
return res_dct
lst = ['a', 1, 'b', 2, 'c', 3]
print(Convert(lst))
Example 3: python list to dictionary
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values))
Example 4: python convert string to list of dictionaries
import json
with open('.listOfDicts.txt', 'r') as file:
dataList = json.loads(file.read().replace('\n', ''))
for dictItem in dataList:
for key , val in dictItem.items():
print( key , val )