Ben W
Ben W

Reputation: 15

Nested list to nested dictionary in python

I have what seems to be a tricky question, but probably quite a simple solution.

I have a nested list that I wish to have the first value of every list contained to be the key within a dictionary. I wish to have every other element contained within that list to be added as a value to that key.

Here is a sample of the nested list:

stations[[1, 'carnegie', 12345, 30],[2, 'london', 12344, 30], [4, 'berlin', 1345563, 30]]

I wish to convert this to a dictionary in the following format:

stations {1:['carnegie', 12345, 30], 2:['london', 12344, 30], 4:['berlin', 1345563, 30]}

The nested list is quite large, so I've only included as sample here :)

My current attempts have yielded the best option as:

newDict = dict.fromkeys(stations,{})

Which gives me:

{1: {}, 2:{}, 4:{}}

To which I'm at a loss how to combine both the keys and values to make my ideal dictionary.

Any help on this would be great.

EDIT:

To add, I'd like to be able to assign a variable name to the dictionary as with the current solution provided below:

{i[0] : i[1:] for i in stations}

This give me the correct output in a loop, but when I assign a variable to it in the loop it gives me the final key:value in the dictionary

newDict = {}
 for y in stations:
   newDict = {y[0] : y[1:]}

print newDict

returns:

{4: ['berlin', 1345563, 30]}

Thanks!

Upvotes: 1

Views: 3553

Answers (2)

Scorpion_God
Scorpion_God

Reputation: 1499

Use a dict comprehension:

{i[0]: i[1:] for i in stations}

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

>>> stations = [[1, 'carnegie', 12345, 30],[2, 'london', 12344, 30], [4, 'berlin', 1345563, 30]]

You can use a dict comprehension

>>> {i[0] : i[1:] for i in stations}
{1: ['carnegie', 12345, 30], 2: ['london', 12344, 30], 4: ['berlin', 1345563, 30]}

Upvotes: 3

Related Questions