操作列表中

时间:2017-05-26 14:17:22

标签: python python-3.x dictionary

我发现在列表中操作字典中的键和项很困难。我想在变量中获取,例如,列表中所有字典中第一个索引键中的第一个索引项:

Dict = [{"top": 1, "bottom": "a", "left": "b"}, {"top": 2, "bottom": "c", "left": "d"}, {"top": 3, "bottom": "e", "left": "sdfasda"}, {"top": 4, "bottom": "f", "left": "g"}]

需要输出:

[1, 2, 3, 4] *#All part of the key "top"*

[a, c, e, f] *#All part of the key "bottom"*

取决于我需要的是哪个键。

我原以为:

for x in Dict:
    print(x("top"))

非常感谢帮助。

2 个答案:

答案 0 :(得分:3)

字典值由索引运算符[key]获取,而不是(key)。最后一个用于调用callables'调用

[x["top"] for x in Dict]

会做的。

答案 1 :(得分:0)

您可以使用列表压缩创建所需的列表:

listTop = [i['top'] for i in Dict]

输出:[1,2,3,4]

执行此操作,您将遍历Dict List中的所有dicts。在那之后,你选择了顶级'每一个的价值,归还它。

要打印它:[print(i) for i in listTop]

相关问题