Reputation: 4960
I have a dictionary with below values, which consists airline code and their perror number.
peq = {
'sg':{'code':9, 'perror':0},
'6e':{'code':17, 'perror':0},
'g8':{'code':25, 'perror':0},
'i7':{'code':33, 'perror':0},
'9h':{'code':41, 'perror':0},
'it':{'code':49, 'perror':0},
'ic':{'code':57, 'perror':0},
'9w':{'code':65, 'perror':0},
's2':{'code':73, 'perror':0},
'ai':{'code':81, 'perror':0}
}
I have a variable which is shown below. perrors consists of error code and acode is the airlines code similar to the one which is mentioned above in peq dictionary
perrors = ['0', '281', '2', '16', '0', '0', '2', '0', '0', '1']
acode = [41, 65, 17, 81, 73, 57, 9, 49, 33, 25]
I have then zipped the above two list in dictionary
>>> ic = dict(zip(acode,perrors))
>>> ic
{65: '281', 25: '1', 49: '0', 81: '16', 41: '0', 17: '2', 9: '2', 73: '0', 57: '0', 33: '0'}
>>>
Now what I am actually trying to solve is to update perror mentioned in the peq dictionary by comparing the ic code (on the left) with the value in the right in peq "perror".
Sorry if i am not being clear but in a nutshell I want to update all the values of perror
mentioned in the peq
dictionary with the values on its right mentioned in the ic
dictionary but first it needs to do comparison whether the code exist in peq
and if it does then update its perror
(peq
dictionary) with ic
value.
Upvotes: 0
Views: 64
Reputation: 7931
You need to iterate the dict
and use the proper key from the zipped list
:
import pprint
peq = {
'sg':{'code':9, 'perror':0},
'6e':{'code':17, 'perror':0},
'g8':{'code':25, 'perror':0},
'i7':{'code':33, 'perror':0},
'9h':{'code':41, 'perror':0},
'it':{'code':49, 'perror':0},
'ic':{'code':57, 'perror':0},
'9w':{'code':65, 'perror':0},
's2':{'code':73, 'perror':0},
'ai':{'code':81, 'perror':0}
}
perrors = ['0', '281', '2', '16', '0', '0', '2', '0', '0', '1']
acode = [41, 65, 17, 81, 73, 57, 9, 49, 33, 25]
ic = dict(zip(acode,perrors))
for k, v in peq.items():
try:
v['perror'] = ic[v['code']]
except KeyError:
print 'failed to find code {} at ic zip'.format(v['code'])
pprint.pprint(peq)
Output:
{'6e': {'code': 17, 'perror': '2'},
'9h': {'code': 41, 'perror': '0'},
'9w': {'code': 65, 'perror': '281'},
'ai': {'code': 81, 'perror': '16'},
'g8': {'code': 25, 'perror': '1'},
'i7': {'code': 33, 'perror': '0'},
'ic': {'code': 57, 'perror': '0'},
'it': {'code': 49, 'perror': '0'},
's2': {'code': 73, 'perror': '0'},
'sg': {'code': 9, 'perror': '2'}}
Upvotes: 1