更改python dict中的键并仅打印值为

时间:2016-08-14 05:57:50

标签: python python-3.x dictionary

我试图操纵一个字典:

op = {'File:Directory': '/var/tmp/Mkbib/Trial2', 'PDF:Title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'PDF:Author': 'V. L. Moruzzi and P. M. Marcus', 'File:FileSize': '636 kB', 'File:FileInodeChangeDate': '2016:08:13 19:45:15+02:00'}

fields = ["author",  "year",  "journal", "title", "publisher"]
new_op = {}
for field in fields:
    # new_op = dict((field, value) for key, value in op.items() if field in key.lower())
    new_op[field] = value for key, value in op.items() if field in key.lower())
    print(new_op)

我的目标是将op的密钥更改为匹配(如果有)field from fields,并使用新密钥创建new_op,如果匹配密钥则创建值。

所以,在上面的例子中,我的new_op应该是:

new_op = {'title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'author': 'V. L. Moruzzi and P. M. Marcus'}

注释行正在运行,但显然为每个项目创建了新的dict,并且还显示了所有循环的打印。

1 个答案:

答案 0 :(得分:3)

您可以在此处使用词典理解。

op = {
    'File:Directory': '/var/tmp/Mkbib/Trial2',
    'PDF:Title': 'Antiferromagnetic-ferromagnetic transition in FeRh',
    'PDF:Author': 'V. L. Moruzzi and P. M. Marcus',
    'File:FileSize': '636 kB',
    'File:FileInodeChangeDate': '2016:08:13 19:45:15+02:00'
}

fields = [
    'author',
    'year',
    'journal',
    'title',
    'publisher'
]

new_op = {
    field: value for field in fields
    for key, value in op.items() if field in key.lower()
}

print(new_op)  # {'title': 'Antiferromagnetic-ferromagnetic transition in FeRh', 'author': 'V. L. Moruzzi and P. M. Marcus'}