i want below list as dictionary
sample_list=['A', 'B', 'C', 'D']
expected dictionary shown below
out_dict = {'A':'B','C':'D'}
you could use:
dict(zip(sample_list[::2], sample_list[1::2]))
where zip
creates the key, value pairs for the new dictionary.
a variant using iterators (and therefore avoid making copies of your list) is to iterate in paris (ehrm... pairs as Matthias pointed out in the comments) over your list with zip(it, it)
and then create the dictionary from that:
it = iter(sample_list)
dct = dict(zip(it, it))
in python>=3.8 you will be able to use an assignment expression and do what you need with this nice one-liner
dct = dict(zip(it := iter(sample_list), it))
You can use the following dictionary comprehension:
{x:y for x,y in zip(sample_list[::2], sample_list[1::2])}
# {'A': 'B', 'C': 'D'}
This Example can cope with uneven lists (which would normally crash python)
sample_list= ['A', 'B', 'C', 'D','E','F','G','H']
output = {}
for i in range(0,len(sample_list),2):
#print(sample_list[i],sample_list[i+1])
if (i+1) < len(sample_list): #Dont need this line, just avoids python
#crashing if the list isn't even.
temp = {sample_list[i]:sample_list[i+1]}
output.update(temp)
else:
print("ERROR: LIST NOT EVEN, WILL NOT INCL. Last Item.")
print(output)
Produces this output:
{'A': 'B', 'C': 'D', 'E': 'F', 'G': 'H'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With