2017-08-08 16 views
0

使用Python 2.7,我有一個任意長的元組的列表(t)其中:列表元組來解釋與綜合鍵

t[0] --> first_name_id 
    t[1] --> first_name 
    t[2] --> last_name_id 
    t[3] --> last_name 

first_name_id和FIRST_NAME應該是集合中是唯一的,但last_name_id和last_name是獨一無二的只在first_name_id/first_name內。

正如你可以看到下面,有一個簡的姓氏是「史密斯」,但ID爲3,而對於「湯姆」的ID爲「史密斯」是「0」

t = [('1', 'Tom', '0', 'Smith'), 
    ('1', 'Tom', '1', 'Johnson'), 
    ('1', 'Tom', '2', 'Williams'), 
    ('32', 'Jane', '0', 'Brown'), 
    ('32', 'Jane', '1', 'David'), 
    ('32', 'Jane', '3', 'Smith'), 
    . 
    . 
    . 
    ] 

我米attepting鞏固這一進一本字典,這樣我可以很快通過FIRST_NAME和姓氏找到ID的元組:

所以,我的數據結構將是:

data_structure = { 
    "Tom": {"first_name_id": "1", "surnames": {"Smith": "0", "Johnson": "1", "Williams": "3"}}, 
    "Jane": {"first_name_id": "32", "surnames": {"Brown": "0", "David": "1", "Smith": "3"}} 
    } 

output = data_structure["Tom"]["first_name_id"],data_structure["Tom"]["surnames"]["Williams"] 

print output 

>>> ('1', '3') 
+3

但究竟是什麼你遇到的麻煩是什麼? – jmoon

回答

0

你想這樣日是什麼?

output = {} 
for first_name_id, first_name, last_name_id, last_name in t: 
    if not first_name in output: 
     output[first_name] = {'first_name_id':first_name_id,'surnames':{}} 
    output[first_name]['surnames'][last_name] = 
0

由於數據已經排序上firstnames和姓名ID,您可以直接在您的數據應用itertools.groupby以小組firstnames和姓名ID,然後從該組數據的其餘部分構造內件類型的字典:

from collections import defaultdict 
from itertools import groupby 

d = defaultdict(dict) 

for (f_id, f), g in groupby(t, lambda x: (x[0], x[1])): 
    d[f]['first_name_id'] = f_id 
    d[f]['surnames'] = dict((k, v) for _, _, v, k in g) 

defaultdict(<class 'dict'>, 
      {'Jane': {'first_name_id': '32', 
         'surnames': {'Brown': '0', 
            'David': '1', 
            'Smith': '3'}}, 
      'Tom': {'first_name_id': '1', 
        'surnames': {'Johnson': '1', 
            'Smith': '0', 
            'Williams': '2'}}})