1

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!

2 Answers 2

3
>>> 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]}
Sign up to request clarification or add additional context in comments.

5 Comments

In Python 3, you can use the expanded iterable unpacking syntax to avoid the index and slice, if you want: {key: value for key, *value in stations}
This does the job. However when I attempt to assign the results for that loop to a variable it only gives me the last key and it's elements. ie: print newDict returns {4: ['berlin', 1345563, 30]} Is there a way to remedy this?
@BenW the dict-comp is already a loop - all you're doing in your loop is keep creating a new dictionary with a single entry each turn... Take cyber's code and do: newDict = {i[0] : i[1:] for i in stations} - there ya go... all done...
@JonClements + Cyber: Had a bit of trouble with that in Eclipse. Realised even changing to 2.76 as the interpreter and explicitly stating so in numerous places in Eclipse it just wouldn't work. So I tried a restart and now it's all hunky dory. Thanks everyone!
@BenW don't forget to accept Cyber's answer if it's worked for you
1

Use a dict comprehension:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.