从使用列表的Python字典中获取关联值

2024-04-26 02:50:52 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我正在开发一个应用程序,它可以遍历许多不同的数据库对象,比较字符串并返回相关的id、名字和姓氏。目前,我正在构建元组列表,然后用键和值(使用列表)填充字典。接下来我要做的是找到最大百分比,然后从字典中返回相关的fist和last name。我知道描述有点混乱,因此请查看以下示例和代码:

# 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)

不确定要返回与最大百分比关联的名字和姓氏的位置

我真的很感激你所提供的一切帮助


Tags: name列表字典match名字listcomparefirst
1条回答
网友
1楼 · 发布于 2024-04-26 02:50:52

我希望这将有助于您:

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

相关问题 更多 >