使用键从列表中获取值

时间:2016-04-05 13:08:20

标签: python

在请求"键"时,如何获取列表中项目的值?

e.g。我目前有以下列表:

[{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'} {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]

如何循环打印每个文件的标题和修订

Dictionary = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, ...
KeyList = ['rev', 'time', 'action', 'type', 'title']
for Key in KeyList:
    print Key, "=", Dictionary[title]

我目前收到以下错误:

Traceback (most recent call last):
  File "P:/Scripts/PerforceSearchTool.py", line 45, in <module>
    GetFiles()
  File "P:/Scripts/PerforceSearchTool.py", line 28, in GetFiles
    print Key, "=", Dictionary[depotFile]
NameError: global name 'depotFile' is not defined

最后的列表将包含数千个文件。我希望能够在列表中搜索每个文件标题。并且对于匹配的标题,根据其动作返回其标题。

3 个答案:

答案 0 :(得分:2)

您可以使用for循环:

mylist = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'}, {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]

for i in mylist:
    print("Title: {}, Revision: {}".format(i["title"],i["rev"]))

输出:

Title: test.log, Revision: 1
Title: python.py, Revision: 0
Title: Hello.txt, Revision: 12

答案 1 :(得分:1)

试试这个:

a = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title':     'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title':  'python.py'} {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]

for x in range(len(a)):
    print a[x]['title']
    print a[x]['rev']

问候

答案 2 :(得分:1)

要打印每个元素的标题和修订版,您可以执行以下操作:

min

输出此数据:

Orderable