简体   繁体   中英

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!

>>> 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]}

使用dict理解:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM