我试图操纵一个字典:
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,并且还显示了所有循环的打印。
答案 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'}