如何在新窗口中显示词典列表中每个词典的最后一项?

时间:2013-08-09 14:54:50

标签: python list dictionary

尝试使用TrialHandler编写实验,我成功制作并打印了以下形式的词典列表:

[
    {
        'sentence': 'I am currently working',
        'variable1': 1,
        'variable2': 10
    },
    {
        'sentence': 'How are you today?',
        'variable1': 2,
        'variable2': 20
    }, # ... etc.
]

每个字典都描述了试验的特征。整个词典列表包含实验的所有试验。是否可以选择每个字典的句子部分并在新窗口中逐个显示句子?

2 个答案:

答案 0 :(得分:0)

您可以使用列表理解来获取句子列表:

listOfDict = [{'variable1':1, 'variable2':10, 'sentence':'I am currently working'},
              {'variable1':2, 'variable2':20, 'sentence':'How are you today?'}]

sentences = [d['sentence'] for d in listOfDict]
print(sentences)

打印出来:

['I am currently working', 'How are you today?']

答案 1 :(得分:0)

看看这个:

>>> d = [
...     {
...         'sentence': 'I am currently working',
...         'variable1': 1,
...         'variable2': 10
...     },
...     {
...         'sentence': 'How are you today?',
...         'variable1': 2,
...         'variable2': 20
...     },
... ]
>>>
>>> "\n".join(x['sentence'] for x in d)
'I am currently working\nHow are you today?'
>>> print "\n".join(x['sentence'] for x in d)
I am currently working
How are you today?
>>>