2017-09-28 80 views
0

好的,所以我正在研究可以通過許多不同數據庫對象的應用程序,比較字符串並返回關聯的ID,名和姓。我現在已經將它創建到了構建元組列表的位置,然後使用鍵和值填充字典(使用列表)。接下來我要做的是找到最大百分比,然後從字典中返回相關的拳頭和姓氏。我知道的描述有點混亂,所以請看看下面的例子和代碼:從正在使用列表的Python字典獲取關聯值

# My Dictionary: 
    {'percent': [51.9, 52.3, 81.8, 21.0], 'first_name': ['Bob', 'Bill', 'Matt', 'John'], 'last_name': ['Smith', 'Allen', 'Naran', 'Jacobs']} 

# I would want this to be returned: 
    percent = 81.8 (Max percentage match) 
    first_name = 'Matt' (First name associated with the max percentage match) 
    last_name = 'Naran' (Last name associated with the max percentage match) 

# Code so Far: 
    compare_list = [] 
    compare_dict = {} 

# Builds my list of Tuples 
    compare_list.append(tuple(("percent", percentage))) 
    compare_list.append(tuple(("first_name", first_name))) 
    compare_list.append(tuple(("last_name", last_name))) 

# Builds my Dictionary 
    for x, y in compare_list: 
     compare_dict.setdefault(x, []).append(y) 

不知道去哪裏返回與最大百分比相關聯的第一個和最後一個名字。

我非常感謝您提供的任何和所有幫助!

回答

0

我希望這將幫助你:

data = {'percent': [51.9, 52.3, 81.8, 21.0], 'first_name': ['Bob', 'Bill', 'Matt', 'John'], 'last_name': ['Smith', 'Allen', 'Naran', 'Jacobs']} 


percentage_list = data['percent'] 
percentage = max(percentage_list) 
max_index = percentage_list.index(percentage) 

first_name = data['first_name'][max_index] 
last_name = data['last_name'][max_index] 


# Code so Far: 
compare_list = [] 
compare_dict = {} 

# Builds my list of Tuples 
compare_list.append(tuple(("percent", percentage))) 
compare_list.append(tuple(("first_name", first_name))) 
compare_list.append(tuple(("last_name", last_name))) 

# Builds my Dictionary 
for x, y in compare_list: 
    compare_dict.setdefault(x, []).append(y) 

print compare_dict 
+1

完美!這正是我所期待的 –

相關問題