[英]Getting associated values from Python dictionary that is using lists
Ok, so I am working on an application that can go through a number of different database objects, compare the string and return the associated id, first name and last name. 好的,所以我正在开发一个可以通过许多不同的数据库对象,比较字符串并返回关联的ID,名字和姓氏的应用程序。 I currently have it to where I am building a list of tuples and then populating a dictionary with the key and values(using a list).
我目前在建立元组列表的地方,然后用键和值(使用列表)填充字典。 What I want to do next is find the Max percentage and then return the associated fist and last name from the dictionary.
我接下来要做的是找到最大百分比,然后从字典中返回相关的拳头和姓氏。 I know the description is a little confusing so please look at the below examples and code:
我知道说明有些混乱,因此请查看以下示例和代码:
# 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)
Not sure where to go to return the first and last name associated with the Max percentage. 不确定要返回与最大百分比相关的名字和姓氏的位置。
I really appreciate any and all help that you provide! 非常感谢您提供的所有帮助!
I hope this will help you: 我希望这能帮到您:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.