[英]Comparing values in two list and updating it into the dictionary
I have a dictionary with below values, which consists airline code and their perror number. 我有以下值的字典,它由航空公司代码及其PERROR号。
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由错误代码组成, acode是航空公司代码,与peq词典中上面提到的代码类似
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". 现在什么,我其实是想解决的是通过在PEQ“PERROR”右侧的IC代码(左侧)与值进行比较,以更新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. 抱歉,如果我不清楚,但总而言之,我想用
ic
字典中提到的右侧值更新peq
字典中提到的perror
所有值,但首先需要比较一下代码是否存在于peq
并且如果确实这样做,则使用ic
值更新其perror
( peq
字典)。
You need to iterate the dict
and use the proper key from the zipped list
: 您需要迭代
dict
并使用压缩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'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.