python - 从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 元素元组列表的信息。
关于如何解决这个问题的任何提示?
解决方案
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
推荐阅读
- sql-server - 通过短信发送数据到云服务器
- node.js - app.get 不是 express.js 中的函数
- jsf - 如何使用primefaces中的选择制作分组数据表?
- javascript - 使用画布 globalAlpha 淡化
- c# - 一个或多个实体的验证失败。请参阅“EntityValidationErrors”属性以获取更多详细信息,请帮助我
- php - MySQL 从 pdo lastInsertID 获取 0
- java - Java HashMap:将桶实现更改为线性探测方法
- regex - Bash - 匹配正则表达式的多行数(可能是oneliner?)
- python - Pygame 全屏模式故障
- heroku - Google OAuth2:错误 401 - invalid_client