首页 > 解决方案 > 从python中的元组列表中返回带有2个键的字典

问题描述

我有一个看起来像这样的元组列表。

people = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]

我正在尝试创建一个函数。它有 2 个参数 function(people, name) 该函数应该返回一个带有两个键“age”和“gender”的字典,其值来自元组中的值,该元组包含作为函数的第二个参数传递的名称。如果在元组列表中找不到该名称,则返回“None”。

我正在努力创建一个函数,因为我似乎找不到任何有关如何处理 3 元素元组列表的信息。

关于如何解决这个问题的任何提示?

标签: pythonfunctiontuples

解决方案


people = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]

def my_func(people, name:str):
    b = {}
    for person in people:
        if person[0] == name:
            b["Age"] = person[1]
            b["Gender"] = person[2]
    if len(b)>0:
        return b
    else:
        return None
        

c = my_func(people, 'Rachel')
print(c)
d = my_func(people, 'Diana')
print("\n" + str(d))

我的输出:

{'Age': 24, 'Gender': 'F'}

None

推荐阅读