I'm trying to take an existing dict with, say, five possible entries and move its entries into a new dict, 'translating' the keys along the way. The keys of the first dict are structured in a way that the move cannot be done procedurally. There is no guarantee that all of the entries will be present in the first dict.
In order to avoid KeyError, each entry can be assigned within its own try
block
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'],
}
Perhaps a better way is to check if the entry exists in the first dict and then assign it.
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']
...
In either case, is there a way to condense this? When the number of elements is large it seems like this would become unnecessarily bulky. Is there a way to iterate through the relationships without creating a try
block for each?
You could do this with a loop:
# 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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句