Want to change an element of a list to a dictionary key in python

Viewed 53

I want to change a list to a dictionary and also want to make the first element of the list as key of dictionary and other elements will be the result of this key in dictionary. Thanks in advance.

This what I have :

lst = ['a', 'b', 'c', 'd']
print (list)
['a', 'b', 'c', 'd']

and this is what I desir:

dic = {'a':['b', 'c', 'd']}
print(dic)
{'a': ['b', 'c', 'd']}

or

print (dic['a'])
['b', 'c', 'd']
2 Answers

you can try:

lst = ['a', 'b', 'c', 'd']
dct = {lst[0]:lst[1:]}

It will give you the desired result

I thought of a function in case you need to do do this for several lists.

def todict (lst):
    first, *rest = lst
    return {first: rest}

In[1]: todict(lst)
Out[1]: {'a': ['b', 'c', 'd']}
Related