2011-12-26 79 views
1

我有具有以下結構的字典的字典:從Python字典創建EdgeList都

1:{'Amendment': '1', 
    'status': 'Stadf\xc3\xa6stet', 
    'Name': 'Bodil Kornbek', 
    'title': 'L 1 Forslag til till\xc3\xa6gsbevillingslov for 2004.', 
    'fremsat': '2005-03-04', 
    'Vote.Numeric': '2', 
    'PSession': '1', 
    'vedtaget': '2005-04-12', 
    'Lsession': '3', 
    'Voteid': '38', 
    'Month': '4', 
    'Year': '2005', 
    'Vote': 'Frav\xc3\xa6rende', 
    'Party': 'KD', 
    'Law': 'L 1', 
    'ministerie': 'Finansministeriet'} 

鍵範圍從1到約500000,並且每個嵌套字典包含關於一名丹麥議會一名成員的信息。此外還有一些信息可以確定成員投票的獨特投票。我希望每位成員都能提取該成員活躍的所有選票,並將該成員的投票行爲與所有在同一選票子集上活躍的其他成員進行比較。

理想情況下每個成員的我該成員比較一個其他成員在哪裏,他們積極投票,並計算選票,他們投同他們所有的普通票的比例。如果該比例大於比如0.65,則該對被添加到列表中。

所以最終的結果應該與格式列表:

[member1, member2 
member1, member4 
member1, member7 
member2, member5 
etc.. 
] 

我誰能告訴我這到底是怎麼在Python做呢?

+0

我覺得你的問題是相當不明確。你的嵌套字典的完整內容對於這個問題是無關緊要的。你有一個數據結構,你的成員實際上列出了嗎? – Alex

+0

唯一標識一個成員的是什麼?這個名字,還是別的? –

+0

@Karl:標識成員的變量只是名稱,沒有具有相同名稱的成員。 –

回答

4

首先,讓我們轉換數據(我會在這裏做一些假設),以便字典的鍵是議會成員(由Name標識),每個數據都是他們如何投票的映射(Vote.Numeric )對每個問題(Voteid),所以Voteid s爲在該子字典鍵。我們可以將其餘的信息放棄爲不相關的。

非花哨的程序方式:

member_to_votes = defaultdict(dict) 
for item in vote_data: 
    member_to_votes[item['Name']][item['Voteid']] = item['Vote.Numeric'] 

現在,讓我們定義兩個投票記錄之間的相似性:

def votes_agree(member_a, member_b, threshold): 
    # Find the union of issues they voted on... 
    issues = set(member_a.keys()).union(member_b.keys()) 
    # See how many of these they voted the same way on (we use a placeholder 
    # if one member did not vote on the issue, so that they automatically 
    # disagree) and compare the fraction of agreeing votes to the threshold. 
    # There is a little hack in here: `True` is 1 in a numeric context, and 
    # `False` is zero, so we can add up the boolean results directly. 
    return sum(
     member_a.get(issue, None) == member_b.get(issue, None) 
     for issue in issues 
    )/float(len(issues)) >= threshold 

現在我們可以創建所有對成員的,看看哪些同意:

def agreeing_members(member_to_votes, threshold): 
    return [ 
     [a, b] for a, b in itertools.combinations(member_to_votes.keys(), 2) 
     if votes_agree(member_to_votes[a], member_to_votes[b], threshold) 
    ] 
+0

但是,如果你能看到如何... :) –

+0

感謝您的答案卡爾,直接從CSV文件創建'member_to_votes'會更好!每當我嘗試運行defaultdict(字典),我得到的消息:類型錯誤:第一個參數必須是可調用 –

+0

奇怪。你使用的是什麼版本的Python?這個對我有用。你有沒有在某處重複使用'dict'作爲變量名?不要那樣做;這是一個內置的類型(字典對象類型)的名稱。 –