我正试图用一个现有的dict,例如,五个可能的条目,并将其条目移动到一个新的字典,“翻译”沿途的键。第一个字典的键的结构使得移动不能在程序上完成。无法保证所有条目都出现在第一个词典中。
为了避免KeyError,可以在自己的try
块
first_dict = {
'key_1': foo1,
'key_two': foo2,
'key_three': foo3,
'key_number_4': foo4,
'key_5': foo5
}
second_dict = {}
try:
second_dict['translated_key_1'] = first_dict['key_1']
except KeyError:
pass
try:
second_dict['translated_key_2'] = first_dict['key_two']
except KeyError:
pass
...
try:
second_dict['translated_key_5'] = first_dict['key_5']
except KeyError:
pass
'translated_key_2': first_dict['key_two'],
'translated_key_3': first_dict['key_three'],
'translated_key_4': first_dict['key_number_4'],
'translated_key_5': first_dict['key_5'],
}
或许更好的方法是检查第一个字典中是否存在该条目,然后分配它。
if 'key_1' in first_dict:
second_dict['translated_key_1'] = first_dict['key_1']
if 'key_two' in first_dict:
second_dict['translated_key_2'] = first_dict['key_two']
...
在任何一种情况下,有没有办法压缩这个?当元素的数量很大时,似乎这会变得不必要地笨重。有没有办法迭代关系而不为每个创建try
块?
答案 0 :(得分:7)
你可以用循环来做到这一点:
# This is a simple mapping which associates the old keys with the new ones
translations = {'translated_key_1': 'key_one',
'translated_key_2': 'key_two'}
# iterate through the map
for k,v in translations.iteritems():
# you could also replace with try except
if v in first_dict:
second_dict[k] = first_dict[v]