-1
我遇到了匹配兩個字典列表的問題。在我試圖匹配的代碼下面。如何將字典列表與其他字典值列表中的鍵值不同的地方匹配?
listDict1= [
'{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:16:06"}',
'{"weightMax":150, "weightMin":100, "date":"2017-07-05 12:17:06"}',
'{"weightMax":0, "weightMin":0, "date":"0"}']
listDict2= [
'{"Weight":"138.0","unit":"Kg",
"measurementTime":"2017-07-05 12:15:06",
"receiptTime":"2017-06-30T15:16:09.009-07:00",
"date":1498860969000,"model":"2011",
"manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
'{"Weight":"138.0","unit":"Kg",
"measurementTime":"2017-07-05 12:16:06",
"receiptTime":"2017-06-30T15:16:09.009-07:00",
"date":1498860969000,"model":"2011",
"manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}',
'{"Weight":"188.0","unit":"Kg",
"measurementTime":"2017-07-05 12:17:06",
"receiptTime":"2017-06-30T15:16:09.009-07:00",
"date":1498860969000,"model":"2011",
"manufacturer":"CONTINUA","serialnumber":"SN_WEIGHT082"}']
我需要與listDict2 [ 'measurementTime']
我嘗試下面的代碼匹配listDict1 [ '日期']的值,但它按照列表索引
def matchValValues(listDict1, listDict2):
val1 = []
rpm = []
for i in range(len(listDict1)):
j = dict((k, v) for k, v in ast.literal_eval(listDict1[i]).iteritems())
k = dict((k, v) for k, v in ast.literal_eval(listDict2[i]).iteritems())
#for i in j.keys():
val = j['date']
we = k['measurementTime']
if val in we :
val2 = float(k['Weight'])
max= float(j['weightMax'])
min = float(j['weightMin'])
print "True"
if val2 <= max and val2 >= min:
print "pass"
val1.append(str(j['weightMax'])+'|'+str(j['weightMin']))
rpm.append(k['Weight'])
else:
val1.append(j.copy())
rpm.append(k.copy())
else:
val1.append(j.copy())
rpm.append(k.copy())
print val1
print rpm
匹配預期的輸出: 如果有一個匹配只附加重量和測量時間值,以rpm爲單位 如果有一個匹配,只在val1中附加weightmax,weightmin和date值 否則以rpm和val附加整個不匹配的字典1對應。
電流輸出:
[{'date': '2017-07-05 12:16:06', 'weightMax': 150, 'weightMin': 100},
{'date': '2017-07-05 12:17:06', 'weightMax': 150, 'weightMin': 100},
{'date': '0', 'weightMax': 0, 'weightMin': 0}]
[{'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
'unit': 'Kg', 'manufacturer': 'CONTINUA'},
{'Weight': '138.0', 'measurementTime': '2017-07-05 12:15:06',
'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
'unit': 'Kg', 'manufacturer': 'CONTINUA'},
{'Weight': '188.0', 'measurementTime': '2017-07-05 12:16:06',
'serialnumber': 'SN_WEIGHT082', 'date': 1498860969000L,
'model': '2011', 'receiptTime': '2017-06-30T15:16:09.009-07:00',
'unit': 'Kg', 'manufacturer': 'CONTINUA'}]
你能告訴我該怎麼做嗎?我試圖弄清楚。 –
什麼部分給你帶來麻煩?這有幾個步驟,而SO不是代碼編寫或教程服務。您的代碼顯示您知道如何從字典條目中提取值。在列表中搜索一個值是'index'方法。 'Reverse dictionary'是一個簡單的瀏覽器搜索。 – Prune