我发现很难在列表中操纵字典中的键和项。例如,我想在一个变量中获取列表中所有词典的第一个索引键中的第一个索引项:
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"))
我们将不胜感激。。你知道吗
可以使用列表压缩创建所需的列表:
输出:[1,2,3,4]
这样做,您将迭代Dict列表中的所有Dict。然后,取每个值的“top”值,返回它。你知道吗
要打印它:
[print(i) for i in listTop]
字典值由索引运算符
[key]
获得,而不是(key)
。最后一个用于调用callables的调用。你知道吗就行了。你知道吗
相关问题 更多 >
编程相关推荐