2016-08-10 60 views
0

我有保存記錄的集合,如果一些詞典:匹配值

d1 = {'id':['223','444'],'value_1':['v1','x1']} 
d2 = {'id': ['223','666'],'value_2':['v2','x2']} 
d3 = {'id':['223','444'], 'value_3':['v3','x3']} 

我要搜索所有符合第一庫的ID,並將其保存在一個新的與記錄所有的領域,「_1」,「_2」和「VALUE_3」:

d_4 = {'id':[],'value_1':[],'value_2':[],'value_3':[]} 

如果一條記錄沒有在所有的詞典,我將在這一領域增加「----」存在。所以輸出,在這種情況下,將是:

d_4 

{'id': ['223', '444'], 
'value_1': ['v1', 'x1'], 
'value_2': ['v2', '----'], 
'value_3': ['x3', 'x3']} 

我寫了這個代碼,可以這樣做:

for i,id_d1 in enumerate(d1['id']): 
    d_4['id'].append(id_d1) 
    d_4['value_1'].append(d1['value_1'][i]) 
    if id_d1 in d2['id']: 
     for j,id_d2 in enumerate(d2['id']): 
      if id_d1==id_d2: 
       d_4['value_2'].append(d2['value_2'][j]) 
    else: 
     d_4['value_2'].append('----') 
    if id_d1 in d3['id']: 

     for k,id_d3 in enumerate(d3['id']): 
      if id_d1==id_d3: 
       d_4['value_3'].append(d3['value_3'][j]) 
    else: 
     d_4['value_3'].append('----') 

但並不似乎是一個不錯的辦法。

+1

我明白你的這個權利嗎r記錄有一個'id'成員,它實際上是一個**的**列表,而一個'value_x'成員實際上是一個值列表,每個值都對應一個id,依次爲?也就是說,'d1 ['value_1'] [0]'是與'd1 ['id'] [0]'對應的值? –

+0

這是不明確是否'd1' ids是參考,因爲你說「如果其中一個記錄*不存在於所有字典*我將在該字段中添加'----'。這是否意味着用'd3 = {'id':['223','555'],'value_3':['v3','x3']}'你會有'----''在'd_4'中代表'value_3'和'value_1',然後呢? – zezollo

+0

@MathieuBridon是的,這是正確的 –

回答

1

也許這將幫助你:

代碼:

import sys 
print(sys.version) 

# you should use an iterable for your data 
in_list = [{'id':['223','444'],'value_1':['v1','x1']}, 
    {'id': ['223','666'],'value_2':['v2','x2']}, 
    {'id':['223','444'], 'value_3':['v3','x3']} 
    ] 

print "Input:\n", in_list 

# note that dictionaries are not ordered 
out_dict = {} 
out_dict["id"] = in_list[0]["id"] 
out_dict["value_1"] = in_list[0]["value_1"] 

for i,d in enumerate(in_list[1:]): 
    values = [v[1] for v in d.items() if "value" in v[0]][0] 
    #print(i, d, values) 
    if in_list[i+1]["id"] != in_list[0]["id"]: 
     values[1] = "---" 
    out_dict["value_{}".format(i+2)] = values 

print "Output:\n", out_dict 

日期:

2.7.2 (default, Aug 31 2011, 14:05:14) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build)] 
Input: 
[{'value_1': ['v1', 'x1'], 'id': ['223', '444']}, {'id': ['223', '666'], 'value_2': ['v2', 'x2']}, {'id': ['223', '444'], 'value_3': ['v3', 'x3']}] 
Output: 
{'value_1': ['v1', 'x1'], 'id': ['223', '444'], 'value_3': ['v3', 'x3'], 'value_2': ['v2', '---']} 


更新:修復錯誤,以得到所需的輸出 UPDATE2:我+ 1偏移

+0

如果您確實需要迭代變量:>>> d1 = {「key」:None} >>> i = 1 >>> print(locals( )[「d」+ str(i)] [「key」]) None' – handle