问题
I have a list
of objects:
['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago', '0', ...]
How do I convert this into a dictionary where the keys are the 1st and 5th elements and the values are the 2nd and 6th elements?
dictionary = {'fb_ads_sm': 'Active', 'sm_sg13': 'Pending', ...}
回答1:
You can try to use dict comprehension with list slicing
a = ['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago']
{k: v for k, v in zip(a[::4], a[1::4])}
OR
dict(zip(a[::4], a[1::4]))
Output
{'fb_ads_sm': 'Active', 'sm_sg13': 'Pending'}
回答2:
def Convert(a):
it = iter(lst)
res_dct = dict(zip(it, it))
return res_dct
lst = ['fb_ads_sm', 'Active', '18 hr ago', '23', 'sm_sg13', 'Pending', '12 hr ago']
print(Convert(lst))
回答3:
Try this method: data is your actual list.
dict_list = {}
for i in range(0, len(data)-1, 4):
dict_list[data[i]] = data[i+1]
来源:https://stackoverflow.com/questions/62872148/how-to-convert-a-list-into-a-dictionary-in-python