Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert single list's elements in form of dictionary

i want below list as dictionary

sample_list=['A', 'B', 'C', 'D']

expected dictionary shown below

out_dict = {'A':'B','C':'D'}
like image 676
Ganesh Kharad Avatar asked May 08 '19 10:05

Ganesh Kharad


3 Answers

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))
like image 105
hiro protagonist Avatar answered Nov 20 '22 14:11

hiro protagonist


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'}
like image 23
yatu Avatar answered Nov 20 '22 15:11

yatu


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'}
like image 3
AngusClayto Avatar answered Nov 20 '22 15:11

AngusClayto