简体   繁体   English

嵌套列表到python中的嵌套字典

[英]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 这在循环中为我提供了正确的输出,但是当我在循环中为其分配变量时,它将为我提供最终的key:value在字典中

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 您可以使用dict理解

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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