sheth7
sheth7

Reputation: 349

Converting nested lists to dictionary with self generated keys

My list of lists looks like this:

my_list = [[sub_list_1],[sub_list_2],...,[sub_list_n]]

Desired output

my_dict[1] = [sub_list_1]
my_dict[2] = [sub_list_2]
my_dict[n] = [sub_list_n]

I want the keys for the dictionary to be generated on their own. How can this be achieved in a pythonic way?

I look at certain questions like

but they either provide a list of keys or focus on using some information from the lists as keys.

Alternatively, I tried making a list of keys this way:

my_keys = list(range(len(my_list)))
my_dict = dict(zip(my_keys,my_list)

and it works but, this does not:

my_dict = dict(zip(list(range(len(my_list))),my_list))

This gives me a syntax error.

So in summary:

Upvotes: 1

Views: 169

Answers (4)

Goldwave
Goldwave

Reputation: 599

Your syntax error is caused by your variable name try. try is allready a name in python. see try/except

Upvotes: 2

123
123

Reputation: 813

I received no error message when running your code:

>>> my_list = [["hello1"], ["hello2"]]
>>> my_dict = dict(zip(list(range(len(my_list))), my_list))
>>> my_dict
{1: ['hello1'], 2: ['hello2']}

You can create a dict of lists from a list of lists using a dict comprehension:

my_dict = {i: sub_list for i, sub_list in enumerate(my_list)}

Upvotes: 1

Concorde
Concorde

Reputation: 87

This should do it

my_dict = {my_list.index(i) + 1: i for i in my_list}

Notice that I have added +1 to start at the key 1 instead of 0 to match your expectations

Upvotes: 1

Yossi Levi
Yossi Levi

Reputation: 1268

I would recommend to use a dict comprehension to achieve what you want like in here, moreover I tried your implementation and haven't faced any issues (more details are more than welcome):

my_list = [["sub_list_1"],["sub_list_2"],["sub_list_3"]]
my_dict = dict(zip(list(range(len(my_list))),my_list))
alternative_dict = {iter:item for iter,item in enumerate(my_list)}
print("yours : " + str(my_dict))
print("mine : " + str(alternative_dict))

output:

yours : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
mine : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}

Upvotes: 2

Related Questions